0

So i try to read first and last name (at elev[i].nume) and it doesnt work i looked on other questions still doesnt work

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n;
    struct caract
    {
      char nume[30];
      float medie ;
      float note[4];
      int prom;
      
    };
    scanf("%d", &n);
    struct caract elev[n];
    for(int i=0;i<n;i++)
    {
      scanf("%[^\n]%s", &elev[i].nume);
        elev[i].medie=0.0;
        elev[i].prom=1;
        for(int j=0;j<4;j++)
....
        if(elev[i].prom==1)
        {
            printf("%s ", elev[i].nume);
            printf("%.2f \n", elev[i].medie);
        }
    }
    return 0;
}

I expected to read whole string but only read first word. I know there is a getline in c++ for this

Filip Ion
  • 1
  • 1
  • 1
    `scanf("%[^\n]%s", &elev[i].nume);` has only one target for two format specifiers. I suggest `scanf(" %29[^\n]", elev[i].nume);` note the leading space used to read any pending newline, the length restriction, and the `&` removed. This particular format spec will leave a newline in the buffer, just as formats `%d` `%f` and `%c` etc do. It's not a good idea to attempt cleaning them off after the input, instead ensure the *next* input ignores them. – Weather Vane Nov 05 '22 at 18:18
  • 2
    There's also `getline` in (POSIX) C – Chris Dodd Nov 05 '22 at 18:19
  • You may wish to validate your input before using it in `struct caract elev[n];` If `scanf` does not return `1`, or the user inputs `0`, you get undefined behavior. – Chris Nov 05 '22 at 18:28
  • 1
    *There's also `getline`...* Note that the previous `scanf("%d", &n);` will also leave a newline in the buffer. Try not to mix the input methods unless you are very sure of all the idiosyncrasies. – Weather Vane Nov 05 '22 at 18:34

0 Answers0