簡體   English   中英

如何讀寫 STL C++ 字符串?

[英]How to read and write a STL C++ string?

#include<string>
...
string in;

//How do I store a string from stdin to in?
//
//gets(in) - 16 cannot convert `std::string' to `char*' for argument `1' to 
//char* gets (char*)' 
//
//scanf("%s",in) also gives some weird error

同樣的,我怎么寫出來in ,以標准輸出或文件?

您正在嘗試將 C 風格的 I/O 與 C++ 類型混合。 使用 C++ 時,您應該將std::cinstd::cout流用於控制台輸入和輸出。

#include <string>
#include <iostream>
...
std::string in;
std::string out("hello world");

std::cin >> in;
std::cout << out;

但是當讀取字符串時,std::cin 一旦遇到空格或新行就會停止讀取。 您可能希望使用getline從控制台獲取整行輸入。

std::getline(std::cin, in);

您對文件使用相同的方法(處理非二進制數據時)。

std::ofstream ofs("myfile.txt");

ofs << myString;

有很多方法可以將 stdin 中的文本讀入std::string 不過,關於std::string的事情是它們會根據需要增長,這反過來意味着它們會重新分配。 在內部, std::string有一個指向固定長度緩沖區的指針。 當緩沖區已滿並且您請求向其添加一個或多個字符時, std::string對象將創建一個新的、更大的緩沖區而不是舊緩沖區,並將所有文本移動到新緩沖區。

所有這一切都是說,如果您事先知道要閱讀的文本長度,那么您可以通過避免這些重新分配來提高性能。

#include <iostream>
#include <string>
#include <streambuf>
using namespace std;

// ...
    // if you don't know the length of string ahead of time:
    string in(istreambuf_iterator<char>(cin), istreambuf_iterator<char>());

    // if you do know the length of string:
    in.reserve(TEXT_LENGTH);
    in.assign(istreambuf_iterator<char>(cin), istreambuf_iterator<char>());

    // alternatively (include <algorithm> for this):
    copy(istreambuf_iterator<char>(cin), istreambuf_iterator<char>(),
         back_inserter(in));

以上所有內容都將復制在標准輸入中找到的所有文本,直到文件結束。 如果您只想要一行,請使用std::getline()

#include <string>
#include <iostream>

// ...
    string in;
    while( getline(cin, in) ) {
        // ...
    }

如果您想要單個字符,請使用std::istream::get()

#include <iostream>

// ...
    char ch;
    while( cin.get(ch) ) {
        // ...
    }

C++ 字符串必須使用>><<運算符以及其他 C++ 等效項來讀取和寫入。 但是,如果您想像在 C 中一樣使用 scanf,您始終可以以 C++ 方式讀取字符串並使用 sscanf:

std::string s;
std::getline(cin, s);
sscanf(s.c_str(), "%i%i%c", ...);

輸出字符串的最簡單方法是:

s = "string...";
cout << s;

但是 printf 也可以工作: [fixed printf]

printf("%s", s.c_str());

方法c_str()返回一個指向空終止 ASCII 字符串的指針,所有標准 C 函數都可以使用該字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM