读取未知长度的输入字符串

use*_*494 1 c++ string

在c ++中,我们如何读取用户键入的未知长度(可能包括空白,非常长)的字符串?getline似乎需要知道最大长度.怎么做?

nne*_*neo 6

cin.getline需要知道缓冲区的大小,因为它存储在一个char *.但是,您可以使用std::getline,存储到一个string并可以读取任意数量的文本.

例:

#include <string>
#include <iostream>

int main() {
    std::string line;
    std::cout << "Enter something: " << std::endl;
    std::getline(std::cin, line);
    std::cout << "You typed " << line << std::endl;
}
Run Code Online (Sandbox Code Playgroud)