-2

I'm not able to figure out why the loop in following program is not running exactly testCount times. Please help to make it correct.

#include <iostream>
#include <string>
#include <sstream>

using namespace std;
  int main() {
  size_t testCount;
  cin >> testCount;
  if(testCount < 0 || testCount > 100) return 0;
  int input;
  while(testCount--) {
    string instr;
    getline(cin,instr);
    istringstream iss(instr);
    while(iss >> input) {
      cout << input << endl;
    }
  }
  return 0;
}
Vikas Kaushik
  • 369
  • 2
  • 9

1 Answers1

0

Thanks. I got it. The problem is with getline(). First loop cycle is getting wasted as getline() is taking first line containing just new line character when I pressed enter key after typing testCount value.

std::ws is an input stream manipulator which ignores all whitespaces to the point where the first non-whitespace character is encountered.

Also, getline leaves whitespaces where they are if they don't fit in the line. cin >> ws will discard those.

Here's the bullet proof code:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;
int main() {
  size_t testCount;
  cin >> testCount >> ws;
  if(testCount < 0 || testCount > 100) return 0;
  int input;
  while(testCount--) {
    cout << "testCount " << testCount << endl;
    string instr;
    cin >> ws;
    getline(cin,instr);
    istringstream iss(instr);
    while(iss >> input) {
      cout << input << endl;
    }
  }
  return 0; 
}
Aminah Nuraini
  • 18,120
  • 8
  • 90
  • 108
Vikas Kaushik
  • 369
  • 2
  • 9