简体   繁体   中英

C++ getline(cin, str) giving me extra line

I am a newbie in c++. I am using Cygwin and eclipse in window 7 and I am trying to write a program to just ask user to input a string and just print it out. I have the code below.

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

int main() {
    string mystr;
    cout << "What's your name? ";
    getline (cin, mystr, '\n');
    cout << "Hello " << mystr << ".\n";
    return 0;
}

I also try:

getline(cin, mystr);

They both gave me a out put like below.

output:

What's your name? nick
Hello nick
.

Why is the full stop goes to the next line? Can someone tell what happen and teach me how to fix it.

In gcc 4.6.3

getline (cin, mystr);

and

getline (cin, mystr, '\n');

both are printing the string as you are expecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM