cin and geline

closed account (Gv0G3TCk)
The input was "abc" and the desired result was
"name1: abc",
another input (Let's say"d f"),
"name2:d f"

However, the real output was
"name1: bc
name2: "

What's wrong with my code? Why can't cin and getline be used at the same time?

1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
#include<string>
using namespace std;
int main(){
    string name;
    cin.ignore()>>name;
    cout<<"name1: "<<name<<endl;
    getline(cin,name);
    cout<<"name2: "<<name<<endl;
    return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <iomanip>

int main() {

    std::string name;

    std::cin >> name ; // formatted input: this leaves trailing white space in the input buffer
    std::cout << "name1: " << name << '\n' ;

    // std::cin >> std::ws: read the next line (unformatted input with std::getline) after
    // extracting and discarding the trailing white space  characters (including the new line)
    // remaining in the input buffer (the tail of the previous line) after the last formatted input
    std::getline( std::cin >> std::ws, name ) ;
    std::cout << "name2: " << std::quoted(name) << '\n' ;
}

More information: http://www.cplusplus.com/forum/general/113238/#msg618762
Hello lhcywww,

Line 6 is wrong. It should just be "cin.ignore();". The ignore works on "cin" not name. A better and more often used way of writing line 6 would be:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.

Using line 6 in this code is not needed with just a getline. The only reason for using ".ignore" is when "getline" follows "cin >> aVariable;" because this input will leave the newline in the input buffer. That is when the ".ignore" is used to clear the input buffer before a "getline". On the other hand "getline" will extract the newline from the input buffer.

Try this and see what happens:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
#include<string>

using namespace std;

int main()
{
    string name{ "First Name" };
    //cin.ignore(); //>>name;  // <--- Correct use.
    cout << "name1: " << name << endl;

    getline(cin, name);

    cout << "name2: " << name << endl;

    return 0;
}


Use the gear icon in the top right corner of the shaded code block.

Notice how the code reads better with the use of blank lines and spaces.

Hope that helps,

Andy
closed account (Gv0G3TCk)
Thank you all for your help and reply!
Topic archived. No new replies allowed.