如何读写C++ STL字符串?

19
#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写入stdout或文件中??

3个回答

35
你正在尝试混合使用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会在遇到空格或换行符时停止读取。您可能希望使用std::getline从控制台获取整行输入。

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

当处理非二进制数据时,您可以使用相同的方法来处理文件。

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

ofs << myString;

5

有许多方法可以从标准输入流中读取文本到 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));

以上所有内容都会复制从stdin中找到的所有文本,直到文件结束。如果您只想要一行,请使用std :: getline()

#include <string>
#include <iostream>

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

如果您想要一个单个字符,可以使用std::istream::get()函数:
#include <iostream>

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

1

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也可以工作: [修复的printf]

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

c_str() 方法返回一个指向以空字符结尾的 ASCII 字符串的指针,可以被所有标准 C 函数使用。


2
你使用printf是不安全的,应该使用printf("%s", s.c_str());来防止缓冲区溢出。 - LiraNuna

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接