Home > Blockchain >  How to make std::cin read only a part of the input?
How to make std::cin read only a part of the input?

Time:09-24

I'm making a program that's supposed to read one or two number digits from a line of input. It looks like this:

int N = 0;
cin >> N;
int data[100];

for(int i=0; i<N; i  )
    {
        cin.ignore(5, ' ') >> data[i];
    }

for(int i=0; i<N; i  )
    {
        cout << data[i] << endl;
    }

And the input:

3
1111 22 3 4444 5555
1111 2 3 4444 5555
1111 22 33 4444 5555

The first input is the number of lines the program should expect. After that, each input line looks like the ones above. From those, I want to extract the 2s or 22s. I've learnt about cin.ignore with which I can tell the program to skip a certain amount of characters and also specify and ending character (I think?). The 6th should be the first character and the space after 22 or 2 should be where it stops. If I put in the input above the array will get filled like this instead:

22
3
4444

And the program will already stop after I put in

3
1111 22 3 4444 5555

I'm a very very beginner and I'm pretty sure I messed up someting very obvious, but I can't figure out what.

CodePudding user response:

Read all and discard all but the one you need:

// ...

for(int i=0; i<N; i  )
{
    int dummy;
    std::cin >> dummy >> data[i] >> dummy >> dummy >> dummy;
}

// ...

CodePudding user response:

You need to ignore till the subsequent newline ('\n') as well after ignoring till the first whitespace in a line in the input.

Try this:

#include <iostream>
#include <limits>

int main() {
    int N;
    std::cin >> N;
    
    int data[100];

    for (int i = 0; i < N; i  ) {
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), ' ') >> data[i];
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    
    for (int i = 0; i < N; i  )
        std::cout << data[i] << std::endl;
}
  •  Tags:  
  • c
  • Related