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
how to read line from console and store it into string in c++?
提问by balaji
I have to read a whole line from the console and store it into a std::string
and a char
array,
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);
回答by nagymafla
Maybe
也许
string a;
cin >> a;
cout << a << endl;
Or something like that?
或类似的东西?