Home > Software engineering >  getLine() does't seem to work after first input - C
getLine() does't seem to work after first input - C

Time:06-30

I'm currently new to C and learning the basic syntax.

I'm exploring how getLine() works and I'm trying to compare the standard input and a getline().

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

int main(){

string name1;
string name2;

cout << "Type your name please: ";
cin >> name1;
cout << "Your name is: " << name1 << endl;

cout << endl;

cout << "Type your name again please: ";
cin.ignore();
getline(cin, name2);
cout << "Your name is: " << name2 << endl;

return 0;
}

Expected Output:

Type your name please: John Doe
Your name is: John

Type your name again please: John Doe
Your name is: John Doe

Current Output:

Type your name please: John Doe
Your name is: John

Type your name again please: Your name is: Doe

What may be the issue causing this? Any help would be greatly appreciated.

CodePudding user response:

As you can see cin >> name1; reads only up to the first whitespace. What remains in the input buffer is Doe\n. (Notice the first character is a space).

Now cin.ignore(); will ignore 1 character (the white space in this case). The input buffer now contains Doe\n. See here for more details: https://en.cppreference.com/w/cpp/io/basic_istream/ignore

Next getline(cin, name2); will read all the data up to the next new line. That is Doe, which you get as second output.


I think you wanted to discard the complete input, instead of just one character. This should do it:

cin.ignore(std::numeric_limits<std::streamsize>::max());

CodePudding user response:

You should clear the input stream and ignore not only one character but all in the stream:

#include <iostream>
#include <limits>
#include <string>

int main() {

    std::string name1;
    std::string name2;

    std::cout << "Type your name please: ";
    std::cin >> name1;
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "Your name is: " << name1 << std::endl;

    std::cout << std::endl;

    std::cout << "Type your name again please: ";
    std::getline(std::cin, name2);
    std::cout << "Your name is: " << name2 << std::endl;

    return 0;
}
  • Related