N
N
nkorobkov2016-10-04 16:34:27
C++ / C#
nkorobkov, 2016-10-04 16:34:27

Characters are read incorrectly from the stdin stream, what's the problem?

Task: create a structure that will contain information about chemical elements.
First I did I/O with cin/cout and everything worked great. But my teacher said that everything needs to be done using the C language, so I had to redo everything using the fgets(), printf() and scanf() functions ... And then a problem arose: when reading data from the stdin stream, some fields of the structure are not filled (they are skipped in the loop). Here's what it looks like:
651467d90d7b4615b829af94a5bae591.png
And here's my code:

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

struct ELEMENT {
  char name[10];
  char symbol[2];
  int number;
  char type[10];
  float mass;
  char electrons[10];
};

int main() {
  const int N = 2; //Количество элементов в массиве
  ELEMENT element[N];
  int i;

  // Заполнение массива химических элементов
  for (i = 0; i < N; i++) {
    printf("Enter element %d name: ", i);
    fgets(element[i].name, 10, stdin);
    printf("Enter element %d symbol: ", i);
    fgets(element[i].symbol, 2, stdin);
    printf("Enter element %d number: ", i); //номер элемента
    scanf("%d", &element[i].number);
    printf("Enter element %d type: ", i);
    fgets(element[i].type, 10, stdin);
    printf("Enter element %d mass: ", i);
    scanf("%f", &element[i].number);
    printf("Enter element %d electrons: ", i);
    fgets(element[i].electrons, 10, stdin);
  }
  for (i = 0; i < N; i++) {
    printf("Chimestry elements in our database:\n");
    printf("----------------------------------");
    printf("Name %d: ", i);
    puts(element[i].name);
    printf("Symbol %d: ", i);
    puts(element[i].symbol);
    printf("Number %d: %d\n", i, element[i].number);
    printf("Type %d: ", i);
    puts(element[i].type);
    printf("Mass %d: %f\n", i, element[i].mass);
    printf("Electrons %d: ", i);
    puts(element[i].electrons);
  }

  system("pause");
  return 0;
}

Please tell me what is causing this and how to fix it

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Slava Kryvel, 2016-10-04
@kryvel

The point is how scanf and fgets handle the newline character.
fgets, unlike scanf, accepts the newline character as a valid character and copies it, along with all other input, into a variable.
scanf leaves this character in the buffer.
So when you call fgets after scanf , it immediately gets a newline character as input and finishes reading the data,
choose one way for you to enter data and do not interfere with them.
here is the docs on fgets
cstdio/fgets

A
abcd0x00, 2016-10-06
@abcd0x00

Already answered here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question