[英]How to detect Enter in C++?
I use cin
to input some numbers into my program. 我使用cin
向程序中输入一些数字。 Here is the input format: 这是输入格式:
1' '2' '3' '4' '5' ''\n' //One item includes one number and one space. There is an Enter at the end of input.
I need to input these number one by one into an array until there is an Enter. 我需要将这些数字一一输入到数组中,直到有Enter键为止。 But the cin
cannot detect the '\\n'
. 但是cin
无法检测到'\\n'
。 Does anyone have good idea for that? 有人对此有个好主意吗?
Since the answer-in-commentor has not posted an answer... 由于评论中的答案尚未发布答案,因此...
I guess you were initially reading with int x;
我猜你最初是用int x;
阅读的int x;
... cin >> x
. ... cin >> x
。 The istream::operator>>(int)
function skips leading whitespace, and newlines count as whitespace. istream::operator>>(int)
函数将跳过前导空格,而换行符将计为空格。 So with that approach you could not distinguish 1 2
from 1\\n2
. 因此,使用这种方法无法将1 2
与1\\n2
区分开。
Instead you need to use a function that preserves newlines at least (if not all whitespace). 相反,您需要使用至少保留换行符的函数(如果不是所有空格)。 std::getline
is a good function for this purpose. 为此, std::getline
是一个很好的函数。 You can then turn the line into a stream by using a std::stringstream
. 然后,您可以使用std::stringstream
将行转换为流。
For example: 例如:
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::vector<int> numbers;
std::string line;
std::getline(std::cin, line);
std::istringstream iss(line);
for( int x; iss >> x; )
numbers.emplace_back(x);
// Output to test that it worked
for ( int x : numbers )
std::cout << x << " ";
std::cout << '\n';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.