Linux 如何从控制台读取行并将其存储到 C++ 中的字符串中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5759894/
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-05 03:47:24  来源:igfitidea点击:

how to read line from console and store it into string in c++?

c++linux

提问by balaji

I have to read a whole line from the console and store it into a std::stringand a chararray, e.g.

我必须从控制台读取整行并将其存储到一个std::string和一个char数组中,例如

"Hi this is balaji"

Now I have to read the above string and store it into string. I tried it using the getline()function.

现在我必须读取上面的字符串并将其存储到string. 我尝试使用该getline()功能。

采纳答案by Martin York

Try:

尝试:

#include <string>
#include <iostream>

int main()
{
    std::string line;

    std::getline(std::cin, line);  // read a line from std::cin into line

    std::cout << "Your Line Was (" << line << ")\n";

    std::getline(std::cin, line);  // Waits for the user to hit enter before closing the program
}

回答by zw324

Maybe there's something wrong with how you use cin.getline()?

也许您使用 cin.getline() 的方式有问题?

  cin.getline (name,256);

C++ refence for getline()

getline() 的 C++ 参考

回答by nagymafla

Maybe

也许

string a;
cin >> a;

cout << a << endl;

Or something like that?

或类似的东西?