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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2616968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:06:23  来源:igfitidea点击:

How to read and write a STL C++ string?

c++stringstlio

提问by Moeb

#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

Similarly, how do I write out into stdout or to a file??

同样,如何写出in到标准输出或文件?

回答by Yacoby

You are trying to mix C style I/O with C++ types. When using C++ you should use the std::cin and std::cout streams for console input and output.

您正在尝试将 C 风格的 I/O 与 C++ 类型混合。使用 C++ 时,您应该将 std::cin 和 std::cout 流用于控制台输入和输出。

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

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

But when reading a string std::cin stops reading as soon as it encounters a space or new line. You may want to use getlineto get a entire line of input from the console.

但是当读取字符串时,std::cin 一旦遇到空格或新行就会停止读取。您可能希望使用getline来从控制台获取一整行输入。

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

You use the same methods with a file (when dealing with non binary data).

您对文件使用相同的方法(处理非二进制数据时)。

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

ofs << myString;

回答by wilhelmtell

There are many way to read text from stdin into a std::string. The thing about std::strings though is that they grow as needed, which in turn means they reallocate. Internally a std::stringhas a pointer to a fixed-length buffer. When the buffer is full and you request to add one or more character onto it, the std::stringobject will create a new, larger buffer instead of the old one and move all the text to the new buffer.

有很多方法可以将 stdin 中的文本读入std::string. std::string但是,关于s的事情是它们会根据需要增长,这反过来意味着它们会重新分配。在内部 astd::string有一个指向固定长度缓冲区的指针。当缓冲区已满并且您请求向其添加一个或多个字符时,该std::string对象将创建一个新的、更大的缓冲区而不是旧缓冲区,并将所有文本移动到新缓冲区。

All this to say that if you know the length of text you are about to read beforehand then you can improve performance by avoiding these reallocations.

所有这一切都是说,如果您事先知道要阅读的文本长度,那么您可以通过避免这些重新分配来提高性能。

#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));

All of the above will copy all text found in stdin, untill end-of-file. If you only want a single line, use std::getline():

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

#include <string>
#include <iostream>

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

If you want a single character, use std::istream::get():

如果您想要单个字符,请使用std::istream::get()

#include <iostream>

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

回答by Micha? Trybus

C++ strings must be read and written using >>and <<operators and other C++ equivalents. However, if you want to use scanf as in C, you can always read a string the C++ way and use sscanf with it:

C++ 字符串必须使用>>and<<运算符和其他 C++ 等价物来读取和写入。但是,如果您想像在 C 中一样使用 scanf,您始终可以以 C++ 方式读取字符串并使用 sscanf:

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

The easiest way to output a string is with:

输出字符串的最简单方法是:

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

But printf will work too: [fixed printf]

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

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

The method c_str()returns a pointer to a null-terminated ASCII string, which can be used by all standard C functions.

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