C++ 读取整行输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5882872/
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
Reading a full line of input
提问by Katia
I'm trying to store the input that user enters through console. so I need to include the "enter" and any white space.
我正在尝试存储用户通过控制台输入的输入。所以我需要包括“输入”和任何空格。
But cin
stops giving me input after the first space.
但是cin
在第一个空格后停止给我输入。
Is there a way to read whole lines until CTRL+Z is pressed, or something?
有没有办法在按下 CTRL+Z 之前读取整行?
回答by Konrad Rudolph
is there a way like readLines till CTRL+Z is pressed or something ??
有没有像 readLines 这样的方法,直到按下 CTRL+Z 或其他什么?
Yes, precisely like this, using the free std::getline
function (notthe istream
method of the same name!):
是的,正是这样,使用 freestd::getline
函数(不是istream
同名的方法!):
string line;
while (getline(cin, line)) {
// do something with the line
}
This will read lines (including whitespace, but without ending newline) from the input until either the end of input is reached or cin
signals an error.
这将从输入中读取行(包括空格,但不结束换行符),直到到达输入末尾或cin
发出错误信号。
回答by Katia
#include <iostream>
#include <string>
using namespace std;
int main()
string s;
while( getline( cin, s ) ) {
// do something with s
}
}
回答by Jonny
For my program, I wrote the following bit of code that reads every single character of input until ctrl+x is pressed. Here's the code:
对于我的程序,我编写了以下代码来读取输入的每个字符,直到按下 ctrl+x。这是代码:
char a;
string b;
while (a != 24)
{
cin.get(a);
b=b+a;
}
cout << b;
For Ctrl+z, enter this:
对于 Ctrl+z,输入:
char a;
string b;
while (a != 26)
{
cin.get(a);
b=b+a;
}
cout << b;
I can't confirm that the ctr+z solution works, as I'm on a UNIX machine, and ctrl+z kills the program. It may or may not work for windows, however; You'd have to see for yourself.
我无法确认 ctr+z 解决方案是否有效,因为我在 UNIX 机器上,而 ctrl+z 会终止程序。然而,它可能适用于也可能不适用于 Windows;你得亲眼看看。
回答by peterKnows
#include <string>
#include <iostream>
int main()
{
std::cout << "enter your name: ";
std::string name;
std::getline(std::cin, name);
return 0;
}
回答by koushikkirugulige
You can use the getline function in c++
您可以在 C++ 中使用 getline 函数
#include<iostream>
using namespace std;
int main()
{
char msg[100];
cin.getline(msg,100);
return 0;
}