C++ 在 cin 之后使用 getline(cin, s)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5739937/
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
Using getline(cin, s) after cin
提问by pauliwago
I need the following program to take the entire line of user input and put it into string names:
我需要以下程序来获取用户输入的整行并将其放入字符串名称中:
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
getline(cin, names);
With the cin >> number
command before the getline()
command however (which I'm guessing is the issue), it won't allow me to input names. Why?
但是,使用cin >> number
命令之前的getline()
命令(我猜是问题所在),它不允许我输入名称。为什么?
I heard something about a cin.clear()
command, but I have no idea how this works or why this is even necessary.
我听说了一些关于cin.clear()
命令的事情,但我不知道它是如何工作的,或者为什么这甚至是必要的。
采纳答案by Tony Delroy
cout << "Enter the number: ";
int number;
if (cin >> number)
{
// throw away the rest of the line
char c;
while (cin.get(c) && c != '\n')
if (!std::isspace(c))
{
std::cerr << "ERROR unexpected character '" << c << "' found\n";
exit(EXIT_FAILURE);
}
cout << "Enter names: ";
string name;
// keep getting lines until EOF (or "bad" e.g. error reading redirected file)...
while (getline(cin, name))
...use name...
}
else
{
std::cerr << "ERROR reading number\n";
exit(EXIT_FAILURE);
}
In the code above, this bit...
在上面的代码中,这个位...
char c;
while (cin.get(c) && c != '\n')
if (!std::isspace(c))
{
std::cerr << "ERROR unexpected character '" << c << "' found\n";
exit(EXIT_FAILURE);
}
...checks the rest of the input line after the number contains only whitespace.
...在数字仅包含空格后检查输入行的其余部分。
Why not just use ignore?
为什么不直接使用ignore?
That's pretty verbose, so using ignore
on the stream after >> x
is an oft-recommended alternative way to discard content through to the next newline, but it risks throwing away non-whitespace content and in doing so, overlooking corrupt data in the file. You may or may not care, depending on whether the file's content's trusted, how important it is to avoid processing corrupt data etc..
这非常冗长,因此ignore
在流上使用after>> x
是一种经常推荐的替代方法,可以将内容丢弃到下一个换行符,但它冒着丢弃非空白内容的风险,这样做会忽略文件中的损坏数据。您可能关心也可能不关心,这取决于文件的内容是否可信、避免处理损坏数据的重要性等。
So when would you use clear and ignore?
那么什么时候使用 clear 和 ignore 呢?
So, std::cin.clear()
(and std::cin.igore()
) isn't necessary for this, but is useful for removing error state. For example, if you want to give the user many chances to enter a valid number.
因此,std::cin.clear()
(和std::cin.igore()
) 不是必需的,但对于删除错误状态很有用。例如,如果您想让用户有很多机会输入有效数字。
int x;
while (std::cout << "Enter a number: " &&
!(std::cin >> x))
{
if (std::cin.eof())
{
std::cerr << "ERROR unexpected EOF\n";
exit(EXIT_FAILURE);
}
std::cin.clear(); // clear bad/fail/eof flags
// have to ignore non-numeric character that caused cin >> x to
// fail or there's no chance of it working next time; for "cin" it's
// common to remove the entire suspect line and re-prompt the user for
// input.
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
}
Can't it be simpler with skipws or similar?
用skipws或类似的东西不能更简单吗?
Another simple but half-baked alternative to ignore
for your original requirement is using std::skipws
to skip any amount of whitespace before reading lines...
另一个简单但半生不熟的替代方案ignore
是使用std::skipws
在阅读行之前跳过任意数量的空格...
if (std::cin >> number >> std::skipws)
{
while (getline(std::cin, name))
...
...but if it gets input like "1E6" (e.g. some scientist trying to input 1,000,000 but C++ only supports that notation for floating point numbers) won't accept that, you'd end up with number
set to 1
, and E6
read as the first value of name
. Separately, if you had a valid number followed by one or more blank lines, those lines would be silently ignored.
...但如果它得到像“1E6”这样的输入(例如,一些科学家试图输入 1,000,000,但 C++ 只支持浮点数的表示法)不会接受,你最终会number
设置为1
,并E6
阅读为的第一个值name
。另外,如果您有一个有效数字后跟一个或多个空行,这些行将被默默忽略。
回答by Cristiano Miranda
cout << "Enter the number: ";
int number;
cin >> number;
cin.ignore(256, '\n'); // remaining input characters up to the next newline character
// are ignored
cout << "Enter names: ";
string names;
getline(cin, names);
回答by jonsca
Another way of doing it is to put a
另一种方法是放置一个
cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
after your cin>>number;
to flush the input buffer completely (rejecting all of the extra characters until a newline is found). You need to #include <limits>
to get the max()
method.
在您cin>>number;
完全刷新输入缓冲区之后(拒绝所有额外的字符,直到找到换行符)。你需要#include <limits>
得到max()
方法。
回答by Martin York
Try:
尝试:
int number;
cin >> number;
char firstCharacterOfNames;
cin >> firstCharacterOfNames; // This will discard all leading white space.
// including new-line if there happen to be any.
cin.unget(); // Put back the first character of the name.
std::string names;
std::getline(cin, names); // Read the names;
Alternatively. If you know that number and names will always be on different lines.
或者。如果您知道号码和名称将始终位于不同的行上。
cin >> number;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(cin, names);
回答by Rajeev Atmakuri
You can use std::ws to extract any whitespace characters in the input buffer before using getline. Header for std::ws is sstream.
在使用 getline 之前,您可以使用 std::ws 提取输入缓冲区中的任何空白字符。std::ws 的标头是 sstream。
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
cin>>ws;
getline(cin, names);
回答by Vishal Rai
Try cin.ignore() when you use cin before getline() function
在 getline() 函数之前使用 cin 时尝试 cin.ignore()
void inputstu(){
cout << "Enter roll Number:";
cin >> roll_no;
cin.ignore(); //ignore the withspace and enter key
cout << "Enter name:";
getline(cin, stu_name);
}
回答by Aditya Gullapalli
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
getline(cin, names);//works on the \n left behind
getline(cin, names);//continues and rewrites names
its pretty self explainatory, there is a \n left behind in the stream that cin >> number
uses, which gets assigned to names the first time its used. Reusing the getline writes the correct value now.
它非常自我解释,在使用的流中留下了一个 \n cin >> number
,它在第一次使用时被分配给名称。现在重用 getline 会写入正确的值。
回答by pz64_
Or you can flush the input buffer to read the string
或者您可以刷新输入缓冲区以读取字符串
fflush(stdin)
刷新(标准输入)
it is defined in header stdio.h.
它在头文件stdio.h 中定义。
This code works..
此代码有效..
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
fflush(stdin); //FLUSHING STDIN
getline(cin, names);
回答by 1911 Soldier
i just used
我刚用过
getline(cin >> ws,lard.i_npute);
with the standard
与标准
#include <iostream>
header in the instances where I was having problems with carriage returns and the ws manipulator worked. I will probably start embedding looping functions as classes and using constructor and destructor calls atleast.
在我遇到回车问题并且 ws 操纵器工作的情况下的标题。我可能会开始将循环函数嵌入为类,并至少使用构造函数和析构函数调用。
回答by ng?cminh.oss
Conceptually, I think you want each answer to be neatly one line. So why don't you try this?
从概念上讲,我认为您希望每个答案都整齐地排成一行。那你为什么不试试这个呢?
cout << "Enter the number: ";
string line;
getline(cin, line);
int number = std::stoi(line);
cout << "Enter names: ";
string names;
getline(cin, names);
The code consumes the first newline character correctly, gives you the number if the line is correct or throws an exception if it is not. All for free!
代码正确使用第一个换行符,如果行正确,则为您提供编号,否则抛出异常。全部免费!