简体   繁体   中英

Is it possible to use both space and enter for taking input in c++?

I want to make a program that takes a list of numbers and reads the input. The problem is that the input will be taken with both spaces and enters. The values are integers.

An example of the list:

3
2 1 2
2 2 1
5 5 4 3 2 1

Please don't be too hard on me, as I am just learning C++.

#include <iostream>
using namespace std;

int main(){
    unsigned int var;
    cin >> var; cin.get();

    cout << var;
    return 0;
}

So, when pressing either Space or Enter , I want it to take the value of var , instead of only pressing Space .

In your example input, the first number appears to be the number of rows present, and the first number of each row appears to be the number of values present in that row.

If so, then simply write your code logic accordingly, eg:

#include <iostream>
using namespace std;

int main(){
    unsigned int numRows, numValues, var;

    cin >> numRows;
    for(unsigned int i = 0; i < numRows; ++i)
    {
        cin >> numValues;
        for(unsigned int j = 0; j < numValues; ++j)
        {
            cin >> var;
            ...
        }
    }

    return 0;
}

operator>> treats both Space and Enter as whitespace, so you don't need to differentiate between them in this situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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