读取由空格或换行符分隔的输入.

read input separated by whitespace(s) or newline...?

本文关键字:分隔 输入 换行符 空格 读取      更新时间:2023-10-16

我正在从标准输入流中获取输入。如

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/