gjhb

what is the difference between getline and cin?
Last edited on
well if you have spaces you could just use operator << instead of getline and input to an int instead of string.
Try
1
2
3
4
5
6
7
8
9
10
11
int value , column = 0 , row = 0 , matrix[ 3 ][ 3 ];
while (input.good())
{
    input  >> value;
    matrix[ row ][ column ];
    if( column != 2 ) ++column;
    else {
        column = 0;
        ++row;
    }
}


Might be a few small errors but just modify it to yours.

Last edited on
When you have cin >> foo, data is read until either there is a space or a newline (\n) character. For example, if you had:
1
2
3
4
std::string str("");
std::cout << "Enter a sentence: ";
std::cin >> str;
std::cout << '\n' << str << std::endl;

Then your output might be:

Enter a sentence: This is a sentence.
This

As you can see, only one word is read in while the rest is left in the buffer.

getline(cin,foo) is different in that it also reads in spaces. It will only stop at the first newline character or whatever delimiter you decide to set.
The previous code snippet can be expanded to:
1
2
3
4
5
6
7
std::string str(""), str2("");
std::cout << "Enter a sentence: ";
std::cin >> str;
std::cout << '\n' << str << std::endl;
std::cout << "What was left in the buffer: ";
std::getline(cin,str2);
std::cout << str2;

Now your output could look like:

Enter a sentence: This is a sentence.
This
What was left in the buffer: is a sentence.


Another major difference between using cin >> foo and getline(cin,foo) is that the first will leave a newline in the buffer while the latter does not. Therefore, it is recommended to not have a mixture of these two calls in your code. Otherwise, getline(cin,foo) might read in a newline left by a cin >> foo call, and would end up looking as if it were "skipped over."

Additional info:
There is also another version of getline for character array parameters.
 
cin.getline(cstring_holder, number_of_char_to_read);
Last edited on
Topic archived. No new replies allowed.