简体   繁体   中英

I am getting wrong output in my cpp program

 while(t--){
    string str, token, dummy;
    cin.ignore();
    getline(cin ,str);
    int pos = str.find(' ');
    token = str.substr(pos+1);
    str = str.substr(0, 3);
    cout << str << " " <<  token << endl;
}

On giving input as:
add hackerrank
add hacker
find hac
find hak

output comming as:
add hackerrank
dd hacker
ind hac
ind hak

I'm missing first char of my input from second line.

From istream ignore() [emphasis added]

basic_istream& ignore( std::streamsize count = 1, int_type delim = Traits::eof() );

Extracts and discards characters from the input stream until and including delim.

The default value of count is 1 . So, it is ignoring 1 character from input stream as you are calling it without any parameter.

You are observing this behaviour of ignoring first character of input from second line because you might have given some input value before while loop (may be input value for t , like this - cin >> t ) and hit the enter button which is leaving the stray \n in input stream. The first execution of cin.ignore() eating that stray \n character from input stream and from second input string onwards it eating up the first character of your input.

To solve this problem, you can simply add cin.get() just after the input value giving before entering while loop and remove cin.ignore() from loop body.

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