简体   繁体   English

Cin直到输入结束

[英]Cin until end of input

I need to read in a string and then an integer until the user indicates end of input (ctrl-d in linux). 我需要读取一个字符串然后一个整数,直到用户指示输入结束(linux中的ctrl-d)。 Again, I am stuck. 再一次,我被困住了。 Currently I have a while loop: 目前我有一个while循环:

while (getline(cin, line))

However, that gives an entire line and then I cannot seem to separate the string from the integer. 但是,这给出了整行,然后我似乎无法将字符串与整数分开。 Suggestions would be most appreciated! 建议将非常感谢! :) :)

If the string and the integer is separated by whitespace; 如果字符串和整数由空格分隔; Do this: 做这个:

while(std::cin>>your_string>>your_num>>std::ws){}

You can choose your own delimiter, by writing a manipulator yourself. 您可以自己编写操纵器来选择自己的分隔符。

Another approach would be to do it your way, and put the input line into a stringstream and extract the string and numbers from it. 另一种方法是按照自己的方式进行操作,并将输入行放入字符串流中,并从中提取字符串和数字。 That approach seems roundabout to me as you get strings from a stream only to put it into another stream. 这种方法对我来说似乎是迂回的,因为你从流中获取字符串只是为了把它放到另一个流中。

cin>>a

The above statement reads a token from standard input and stores it in the a variable. 上述语句从标准输入中读取标记并将其存储在变量中。 What is less known is that it also returns a bool value. 鲜为人知的是它也返回一个bool值。 When you reach the end of all standard input, the above statement would return false. 当您到达所有标准输入的末尾时,上述语句将返回false。 Use it in an if statement! 在if语句中使用它!

if(c>>a){
  cout<<"End of standard input has been reached!";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM