C ++ CIN enter space characters and Getline () to ignore line breaks at the beginning

Source: Internet
Author: User

1. Enter a space character.

In the following code, you need to press the Enter key twice to display it. Because Getline has three parameters, the third parameter is the string Terminator, that is, when Getline encounters this Terminator, it does not accept input, for example, writing it as Getline (CIN, St, 's'); even if the input is abcsabc, only ABC is displayed.

Therefore, in the case above, some people say that Getline uses the carriage return ('/N') as the terminator by default. The first press enter to end the string, and the second press enter to start output.

#include<iostream>  #include<string>   using namespace std;   int main(){       string s;       getline(cin,s);       cout<<s;       return 0;   }  

(This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/lengyuhong/archive/2009/10/12/4659724.aspx)

However, there is a problem here, that is, if you need to call Getline (CIN, S) consecutively, if you do not do any processing, the input at the beginning of each time is the last Terminator, that is, enter, as a result, the second call is directly terminated (Getline does not ignore the linefeed at the beginning of the line, as long as Getline () encounters a linefeed, even if it is the first character, Getline will also stop reading the character and return it. The solution is as follows:

2. Use cin. Clear () or CIN. Ignore () to skip the initial Terminator.

For example

# Include <iostream> # include <string> using namespace STD; int main () {char STR [8]; cin. getline (STR, 5); cout <STR <Endl; cin. clear (); // if there is no clear, the following input is ignored because the CIN mark is not cleared. getline (STR, 5); cout <STR <Endl; System ("pause"); Return 0 ;}

You can also use cin. Ignore (1) to ignore a character;

Or cin. Ignore (1024, '/N.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.