After entering a number (for example, age), I read the line (for example, the name-surname), but as a result I get an extra empty line. Where does it come from and how to get rid of it?

For example,

struct Person { char firstname[20]; char lastname[20]; int age; }; Person p; cin >> p.age; cin.getline(p.firstname,20); cin.getline(p.lastname,20); 

After that, p.firstname is an empty string, and p.lastname is entered for p.firstname .

Same thing when trying to work with C functions

 scanf("%d",&p.age); fgets(p.firstname,10,stdin); fgets(p.lastname,10,stdin); 
  • The question is incomprehensible. Add a code or some description of the process? - Kromster

3 answers 3

Such a reading problem is usually caused by the fact that after a formatted reading, for example, a line is read. Characters not included in the format data (usually a newline character) remain in the input buffer and are read as a [blank] line on the next reading.

Here’s what a wrong C code might look like:

 fscanf(file,"%d",&intVar); fgets(buf,buflen,file); 

(by itself, the same applies to keyboard input - type scanf("%d",&intVar) ).

Or in C ++:

 inputStream >> intVar; inputStream.getline(buf,buflen); 

There may be other options.

Treatment (if you do not change the logic and reading functions, which, of course, is also possible) consists in resetting the input buffer - ignoring all characters to the end of the line between the formatted input and the next line.

In C ++, this can be done with the following code (which means to ignore all characters up to '\n' including '\n' ):

 inputStream.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

In C, you can explicitly read and ignore all characters to the end of the line:

 while(fgetc(file) != '\n'); 

(Of course, it makes sense to also check for a read error - that the character read is not equal to EOF . When reading from the keyboard, you can simply use stdin instead of file , you can - getchar() .)

Another option in C -

 fscanf(file,"%*[^\n]"); fscanf(file,"%*c"); 

    Another option: skip anything that is not a letter.

     while(!isalpha(file.peek())) file.ignore(); file.getline(buf, buflen); 

      The easiest:

       cin >> p.age; cin.get(); cin.getline(p.firstname,20); cin.getline(p.lastname,20); 

      Those. just add cin.get (); after format input. This call will consume an unwanted newline character in the input buffer.

      • one
        I do not agree - you thereby rely on the fact that the number immediately follows '\n' - and this is not necessary. I agree that verification is needed, but not silently read one character. - Harry