I am a CS student trying to grasp some C++ basic concepts. I am trying to get the input of a user from std::cin and put it to an array.
example :
Input > ab ba cd[Entey key pressed] then I would like the array to contain [ab][ba][cd].
So far I have :
#include <iostream>
#include <string>
int main(int argc, char** argv)
{
std::cout << "Please give all strings seperated with white space (eg. ab ba cd) : ";
std::string input[12];
int i=0;
while(std::cin >> input[i])
{
if(input[i].compare("\n")) break;
i++;
}
//This will print contents of input[].
for(int k = 0 ; k < 12 ; k++)
{
std::cout << "input[" << k << "] = " << input[k] << std::endl;
}
return 0;
}
But unfortunately this only stores the first string (in this example "ab") in the first index of the array.
If I comment out the if(input[i].compare("\n")) break; a Segmentation fault will be produced. I guess because I exceed the memory allocated for the array and write in a place i shouldnt.
From what I understand so far std::cin will first put ab in input[0] of the array, and keep the remaining string [ba cd] in the stream, then on the next loop (after i++) [ba cd] will still be in the stream, cin will not read further from the keyboard (since something is on the stream) and it should put the string ba on input[1], etc. Please correct me if I am wrong.
Note : This is not homework. My course starts in about 1 month. Any help greatly appreciated. Thanks in advance