Your code is bizarre. Your main mistakes are:
(a) You put the same string "1 2 3 4 5 6 7 8 9" into the stringstream TEN times!
(b) You specified 10 numbers and then gave it 9 as input!
Note that ALL your second line of input is taken in on line 12.
I suspect what you intended would be something like the following. Note that the input is only put into the stringstream (or "internal file") once. Make sure that you give it TEN numbers at input; thus
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
int n;
cin >> n;
int *data = new int[n];
string one;
stringstream two;
getline(cin >> ws, one); // <=== all input taken here in one go
two << one; // <=== string is only put in the stringstream ONCE
for(int i = 0; i < n; i++){ // <=== your loop is only to fill data[] from the stringstream
two >> *(data+i);
}
for(int i = 0; i < n; i++){
cout << *(data+i) << " ";
}
cout << "test " << *(data+8) << endl;
system("pause");
return 0;
}
|
10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 test 9 |
So what happened in your original code? Well you put the same (
nine) numbers in the stringstream one after another
n(=10) times ... and you didn't have a following gap. So, after your first loop your stringstream called "two" actually held (!)
1 2 3 4 5 6 7 8 91 2 3 4 5 6 7 8 91 2 3 4 5 6 7 8 91 2 3 4 5 6 7 8 91 2 3 4 5 6 7 8 91 2 3 4 5 6 7 8 91 2 3 4 5 6 7 8 91 2 3 4 5 6 7 8 91 2 3 4 5 6 7 8 91 2 3 4 5 6 7 8 9 |
(as you could check with
cout << two.str() << '\n';
Note that there is no gap between each 9 and the next one, so it will be read back as 91.
So, the ten numbers assigned to data[] were:
1 2 3 4 5 6 7 8 91 2
and the (1+8)
th one of those is 91. As your program dutifully wrote out for you.