CorbinMc
CorbinMc

Reputation: 588

C++ std::cin producing extra input

I am new to C++ and attempting to tackle some basic CodeJam problems. I am working on Reverse Words. I am running my code (in a unix environment) by piping in and out of the compiled executable: ./compiled.program < input_file.in > output_file.out

Here is my input (input_file.in):

3
this is a test
foobar
all your base

I would EXPECT the output:

test a is this
foobar
base your all

However, I get the output (output_file.out):


test a is this
foobar

(yes, that space in the beginning was intentional)

Here is my source code:

#include <string>                                                                                                           
#include <iostream>

int main()
{
      int number_of_cases;
      std::cin >> number_of_cases; 

      for (int i=1; i<=number_of_cases; i++) {
          std::cerr << i << std::endl;

          std::string input = ""; 
          std::getline(std::cin, input);

          while (true) {
              int pos = input.find_last_of(" ");
              if (pos == -1) {
                    std::cout << input;
                    break;
              }   
              std::cout << input.substr(pos+1)+" ";
              input.resize(pos);
        }   
        std::cout << std::endl;
    }   
    return 0;
}

The problem to me seems to be that another source of input (a blank source of input) is being read from between 3 and this is a test but for the life of me I cannot find out why. So that is my question: Why is this other source of input being read from?

Any help is greatly appreciated. Thank you so much in advance!

Upvotes: 3

Views: 767

Answers (2)

ronaflx
ronaflx

Reputation: 53

In your program and sample input, when you input '3', I exactly input a character 3 and a character '\n'. So cin reads the character of integer only and leaves the '\n' in input buffer. std::getline reads the '\n' in the first iteration.

Upvotes: 2

M.M
M.M

Reputation: 141633

The line

std::cin >> number_of_cases; 

reads in 3 but stops there, leaving the newline in the stream.

So for i == 1, std::getline(std::cin, input); just reads the newline from the end of the first line. Since this contains no spaces, you trigger std::cout << input; and then break down to std::cout << std::endl, generating your blank line.

Then the count of 3 runs out before getting to all your base.

To fix this you could do a dummy call to getline before entering the loop (this will have the bonus of consuming any trailing whitespace too).

Upvotes: 3

Related Questions