读取由空格或换行符分隔的输入.
read input separated by whitespace(s) or newline...?
我正在从标准输入流中获取输入。如
1 2 3 4 5
或
1
2
3
4
5
我正在使用:
std::string in;
std::getline(std::cin, in);
但这只是抓住了换行符,对吗?我如何获得输入,无论它们是用换行符还是空格分隔的,只使用iostamp、string和cstdlib?
只需使用:
your_type x;
while (std::cin >> x)
{
// use x
}
默认情况下,operator>>
将跳过空白。你可以把东西串起来,一次读取几个变量:
if (std::cin >> my_string >> my_number)
// use them both
getline()
在一行中读取所有内容,无论它是空的还是包含几十个空格分隔的元素。如果您提供可选的替代分隔符ala getline(std::cin, my_string, ' ')
,它仍然不会达到您想要的效果,例如选项卡将被读取到my_string
中。
这可能不需要,但您可能很快就会感兴趣的一个相当常见的要求是读取一行换行符,然后将其拆分为多个组件。。。
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)
...
}
使用'q'
作为getline
的可选参数。
#include <iostream>
#include <sstream>
int main() {
std::string numbers_str;
getline( std::cin, numbers_str, 'q' );
int number;
for ( std::istringstream numbers_iss( numbers_str );
numbers_iss >> number; ) {
std::cout << number << ' ';
}
}
http://ideone.com/I2vWl
std::getline(流,从哪里到?,分隔符即
std::string in;
std::getline(std::cin, in, ' '); //will split on space
或者你可以读一行,然后根据你想要的分隔符来标记它。
用户按回车键或空格键是相同的。
int count = 5;
int list[count]; // array of known length
cout << "enter the sequence of " << count << " numbers space separated: ";
// user inputs values space separated in one line. Inputs more than the count are discarded.
for (int i=0; i<count; i++) {
cin >> list[i];
}
#include <iostream>
using namespace std;
string getWord(istream& in)
{
int c;
string word;
// TODO: remove whitespace from begining of stream ?
while( !in.eof() )
{
c = in.get();
if( c == ' ' || c == 't' || c == 'n' ) break;
word += c;
}
return word;
}
int main()
{
string word;
do {
word = getWord(cin);
cout << "[" << word << "]";
} while( word != "#");
return 0;
}
int main()
{
int m;
while(cin>>m)
{
}
}
如果是空格分隔的或行分隔的,这将从标准输入读取。
简单使用:
字符串
getline(cin>>ws,line(;
如下所述:https://www.geeksforgeeks.org/problem-with-getline-after-cin/
相关文章:
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- C++逗号分隔的输入数组代码过早退出
- 获取带有字符 X 的输入 X/X/etc 并用斜杠 / 分隔它
- 获取由空格分隔的未知大小的单行输入,并将其存储到整数数组中
- 如果用户输入两个或多个由空格分隔的字符串C++如何防止缓冲区溢出?
- 使用运算符将分隔的输入分隔>>变量
- 来自 2 个不同向量的输入,用逗号分隔
- 如何将输入重定向与特殊整数作为分隔线和直至EOF
- 按标记分隔输入
- 如何在用空格分隔的行中获得无限的输入
- 我如何使用CIN输入整数,每个数字都被逗号分隔
- 如何使用符号分隔字符串而不是空格的输入字符串流
- C++:如何输入用逗号(,)分隔的值
- 以C++分隔用户输入的时间
- 如何读取用户输入的逗号分隔整数
- 在 cpp 中使用 getline 输入数组中的空格分隔数字
- 分隔输入C++
- 避免在空格分隔输入后忽略()
- 使用getline分隔输入,使用逗号作为分隔符
- 如何检查cin中的空间分隔输入是否为严格双输入