getline(cin,line) cin >> line difference

Write your question here.

if i use getline in this code
suppose input be 123 12 1
then output would be 123 12 1 as expected
but if i use cin instead,then the output would be 123 0 0
is there any difference between the two function in this case?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  Put the code you need help with here.

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;

int main(int argc, const char * argv[]) {
    // insert code here...
    string a;
    stringstream ss;
    int tmp;
    vector<int> v;
    getline(cin ,a);
    //cin >>a;     
    ss << a;
    while(ss >> tmp)
    {
        v.push_back(tmp);
    }
    cout << v[0]<<endl << v[1] << endl << v[2] <<endl;
    return 0;
}
getline does raw, unformatted input. It really reads whole line as is.

The >> is formatted input. First, it skips all leading whitespace. It also treats whitespace as delimiter, so input ends at the end of the first word.

Both functions have reference documentation on this site with more verbose explanation.
Topic archived. No new replies allowed.