0

I'm trying to read 3 string separately from user input, it all contains numbers separated by white spaces for example "1 2 3". I will read in three lines and store these number in a vector of integer

However the program stop reading the string after I enter "1 2 3"

I'm expecting to enter "1 2 3" first, then enter "4 5 7", then " 8 9 0", and add all these number to the vector.

the print out look like this

Enter the puzzle
1 2 3
123

I'm expecting something like this

Enter the puzzle
1 2 3
4 5 6
7 8 9
1234567890

Where could the problem be? I tried the following

#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <sstream>

using namespace std;


int main(){
  vector<int> arr;
  cout << "Enter the puzzle" << endl;
  string line1;
  string line2;
  string line3;
  cin >> line1;
  cin >> line2;
  cin >> line3;


  istringstream is(line1);
  int num;
  while(is>>num){
    arr.push_back(num);
  }
  istringstream is2(line2);
  while(is2>>num){
    arr.push_back(num);
  }

  istringstream is3(line3);
  while(is3>>num){
    arr.push_back(num);
  }

  for(int i = 0; i < arr.size(); i++){
    cout << arr[i];
  }


  return 0;
}

Does the problem exist because of isstringstream?

gaurav bharadwaj
  • 1,669
  • 1
  • 12
  • 29
  • Can you explain in English how your program is supposed to know how many lines there are? – Botje Nov 18 '20 at 08:37
  • 2
    Does this answer your question? [Read file line by line using ifstream in C++](https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c) – Botje Nov 18 '20 at 08:38
  • A very good first step is often to immediately print your inputs and see what they really are. – molbdnilo Nov 18 '20 at 08:39
  • 2
    Why do you need to read line by line? The entire file is numbers separated by whitespace. – molbdnilo Nov 18 '20 at 08:41
  • 3
    When you use the "input" operator `>>` to read strings, it reads *space-delimited* "words". That means `cin >> line1` will read only the first `1` into `line1`. – Some programmer dude Nov 18 '20 at 08:41
  • The problem (with the information known to us) could be solved with only a *single* statement: `std::copy(std::istream_iterator(std::cin), std::istream_iterator(), std::ostream_iterator(std::cout, ""));` – Some programmer dude Nov 18 '20 at 09:03
  • You probably have to separate the strings at the witespaces so you can check the nine numbers seperatly with istringstream – just a guy Nov 18 '20 at 09:08

1 Answers1

0

cin will read only one number.

Instead of using:

cin >> line1;
cin >> line2;
cin >> line3;

use:

getline(cin, line1);
getline(cin, line2);
getline(cin, line3);

for more look here

SHR
  • 7,940
  • 9
  • 38
  • 57