简体   繁体   中英

Should we use cin.ignore() in competitive programming?

The inputs are an integer followed by two strings.

I want to write the following code

cin>>num;
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
getline(cin,string1,'\n');
getline(cin,string2,'\n');

If I omit line 2, the code fails on my compiler. I don't know how an online judge works. Is the cin.ignore() function required? Are the delimiters '\\n' required as well?

Is the cin.ignore() function required?

Yes, otherwise the first getline will get the (perhaps empty) remainder of the line containing the first number.

Are the delimiters '\\n' required as well?

Yes, by default it will ignore all characters including end-of-line. Specify \\n to ignore all characters up to (and including) the end of the current line.

This is something I just discovered today so I am here to share this with you.

When you take inputs for numeric values use

cin>>numberVar>>ws;

This will avoid white spaces and will let you use

getline(cin, stringVar);

Without any problems.

Happy to Help.

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