Home > Net >  How can I correctly keep track of stream position?
How can I correctly keep track of stream position?

Time:12-28

I am writing a program which requires me to take in double inputs from the user in a very specific way, so I'm learning about streams.

In the end, my goal is to force the user to format their input in the way I desire, which is:

2.0 3.0 4.0 -> doubles (or integers) with spaces in between and no trailing spaces

I've been using a std::istringstream to read inputs in a way akin to the following example:

#include <iostream>
#include <sstream>
using namespace std;

int main(){
    int a[5] = {0};
    
    while (1){
        cout << "Input: ";
        string s;
        getline(cin, s);
        istringstream buffer(s);
        
        for (int i = 0 ; i < 5 ; i  )
            buffer >> a[i];
        
        for (int i = 0 ; i < 5 ; i  )
            cout << a[i] << " ";
        cout << endl;
    }
}

My question is about the following terminal input/output:

Input: 1 2 3 4 5
1 2 3 4 5 
Input: a b c d e
0 2 3 4 5 

Why is the output for the characters being put into integers the way it is?

Here is another example:

Input: 5 6 7 8 9
5 6 7 8 9 
Input: a b c d e
0 6 7 8 9 

It seems to be defaulting to 0 for the first encountered character, and then reusing the rest of the stream, which is why I'm asking about stream position.

My expectations:

  1. Either it would be the corresponding ASCII numerals.

  2. They would all be 0, since (for a reason that I would like to know), characters inputted from a stream into an integer tend to default to 0.

I believe the output being the way it is has to do with the stream position, and I would like it explained (along with an answer on the defaulting 0 characters).

Basically, I'm curious about streams and would like to know more about how they're handled, and this seems like a quirk that could highlight that.

CodePudding user response:

Here's the full explanation for your output.

I'm concentrating on the input of a.

First action is that cin >> a[i]; sets a[i] to zero.

Second action is that the read fails because a is not a valid integer. This puts the cin stream into an error state.

Third action is that cin >> a[i]; returns and the programs prints the value from step one.

Now the stream is in an error state (from step two) all subsequent reads fail, with no change to any a[i] so the previous values are printed.

So nothing to do with stream position.

  •  Tags:  
  • c
  • Related