Home > Blockchain >  How to save excess user inputs? C
How to save excess user inputs? C

Time:10-22

As you know in C one is able to have variables assigned based on a user input via std::cin.

When using std::cin ,if I recall correctly, when there are too many inputs that what is required, then the extra inputs are ignored.

int main(){
    int a, b;
    std::cin >> a >> b;
    std::cout << a << " " << b << endl;
    return 0;
}
Input : 2 4 9 16 32

Output : 2 4

I am looking to still use the excess information from the user.How does one store the remaining inputs if one doesn't know the amount of excess inputs that the user will type?

CodePudding user response:

answer:

The data stream is not lost, cin still holds the unused data stream.

explain

You can understand cin like this way, it has a stream of date, and each time cin was called, it would check the target variable type and pour (or consume) the date to fill the variable until success or read delimiters or use out the data.

For you above example, cin has "1 2 3 4", and tried to fill the integers a, and b. When it done, cin still holds the data "3 4". The information is not lost.

demo of full code

#include<iostream>
int main(){
    int a, b, c, d;
    std::cin >> a >> b;
    std::cout << a << " " << b << endl;
    std::cin >> c >> d;
    std::cout << c << " " << d << endl;
    return 0;
}
  • Compile and run:

    g   demo.cpp -Wall -o demo.out
    ./demo.out
    
  • Input and Ouput

    1 2 3 4
    1 2
    3 4 
    

P.S. There are different ways of reading input for various purpos. i.e. while loop to into variables into a container, pour the input into a stream data structure, etc. For example, uses stringstreams family data structures.

details could be find in refences like: c basic io

  • Related