问题描述
我从标准输入流中获取输入。如
1 2 3 4 5
或
1
2
3
4
5
我使用的是:
std :: string in;
std :: getline(std :: cin,in);
但是,只是抓住了换行符,正确?
如何获取输入,不管它们是否由换行符OR空格分隔,只使用iosteam,string和cstdlib?只需使用:
your_type x;
while(std :: cin>> x)
{
//使用x
}
operator>>
将跳过空格。你可以链接东西一次读取几个变量:if(std :: cin>> my_string> my_number)
//使用它们
getline / code>读取一行上的所有内容,返回它是空的还是包含数十个空格分隔的元素。如果你提供可选的替代分隔符ala
getline(std :: cin,my_string,'')
它仍然不会做你想要的,标签将被读入my_string
。
这可能不需要,但是一个相当常见的要求,感兴趣的有些时候很快是读取一个换行符,然后拆分成组件...
std :: string线;
while(std :: getline(std :: cin,line))
{
std :: istringstream iss(line);
first_type first_on_line;
second_type second_on_line;
third_type third_on_line;
if(iss>> first_on_line>> second_on_line>> third_on_line)
...
}
I'm grabbing input from a standard input stream. Such as,
1 2 3 4 5
or
1 2 3 4 5
I'm using:
std::string in; std::getline(std::cin, in);
But that just grabs upto the newline, correct? How can I get input whether they are separated by newline OR whitespace(s) using only iosteam, string, and cstdlib?
解决方案Just use:
your_type x; while (std::cin >> x) { // use x }
operator>>
will skip whitespace by default. You can chain things to read several variables at once:if (std::cin >> my_string >> my_number) // use them both
getline()
reads everything on a single line, returning that whether it's empty or contains dozens of space-separated elements. If you provide the optional alternative delimiter alagetline(std::cin, my_string, ' ')
it still won't do what you seem to want, e.g. tabs will be read intomy_string
.Probably not needed for this, but a fairly common requirement that you may be interested in sometime soon is to read a single newline-delimited line, then split it into components...
std::string line; while (std::getline(std::cin, line)) { std::istringstream iss(line); first_type first_on_line; second_type second_on_line; third_type third_on_line; if (iss >> first_on_line >> second_on_line >> third_on_line) ... }
这篇关于读输入由空格或换行符分隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!