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

8

26

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?

Parthenogenesis answered 21/4, 2011 at 2:34 Comment(2)
If newline isn't the terminating condition, then what is? I.e., how should getline know when to return?Ornithopod
The program will take input until it reaches 'q', at which point the program will quit. but it needs to read in the 'q'. And until then, I want to take input regardless of whether input is separated by a space or a newline or mix and matched.Parthenogenesis
E
38

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 ala getline(std::cin, my_string, ' ') it still won't do what you seem to want, e.g. tabs will be read into my_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)
        ...
}
Eglanteen answered 21/4, 2011 at 2:43 Comment(2)
Your if (std::cin >> my_string >> my_number) handles scenarios where numbers may occur both horizontally and/or vertically.Patisserie
@lifebalance: yes, though if more control/format-verification is needed. the last part of my answer shows how to read lines first, then parse the "horizontal" elements therein.Eglanteen
R
5

Use 'q' as the the optional argument to 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

Roney answered 21/4, 2011 at 2:57 Comment(0)
K
2

std::getline( stream, where to?, delimiter ie

std::string in;
std::getline(std::cin, in, ' '); //will split on space

or you can read in a line, then tokenize it based on whichever delimiter you wish.

Kigali answered 21/4, 2011 at 2:45 Comment(2)
Except that won't split on newline OR whitespace either.Isagoge
Is there no sane C++ way to get text?Tauten
B
1

the user pressing enter or spaces is the same.

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];
}
Blythebm answered 12/9, 2014 at 20:57 Comment(0)
N
1

use cin.peek() to check for newline after reading a single value. This way you can read unknown number of value in a space separated string. Check the example code.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    vector<int> i;
    int n;
    while (cin >> n) {
        i.push_back(n);
        if (cin.peek() == '\n')
            break;
    }

    cout << i.size() << '\n';
    return 0;
}
Notwithstanding answered 26/10, 2023 at 20:41 Comment(0)
M
0
#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;
}
Magenmagena answered 24/5, 2013 at 14:30 Comment(0)
A
0
int main()
{
    int m;
    while(cin>>m)
    {
    }
}

This would read from standard input if it space separated or line separated .

Arlinearlington answered 20/1, 2016 at 21:2 Comment(0)
N
0

Simply use:

string line;
getline(cin >> ws, line);

It is described here: https://www.geeksforgeeks.org/problem-with-getline-after-cin/

Nedry answered 6/4, 2022 at 7:29 Comment(4)
This question has many answers, some of which very high-quality with explanations. Why the answer here?Department
@Department Personally, the answers above didn't solve my problem directly, therefore I added the comment. For beginners the answer as described in the link can give some additional benefit and hopefully solve it directly Thanks for your understanding.Nedry
If it was meant as a comment, add it as a comment and not an answerDepartment
There is no "answer above", at least not reliably, becaue sorting is individually configurable on StackOverflow. E.g. in my sorting your post is first beneath the question. Please move your explanation into the answer post itself by editing it. Try for How to Answer.Prindle

© 2022 - 2024 — McMap. All rights reserved.