String reading with two or more names

0

How do I read a string with a compound name for example: "Vitor Martins"? I'm doing this program that stores a student's name and grade, but it gives a bug when entering two names.

    #include<stdio.h>
    #include<string.h>

    #define alunos 3

int main(){
int x;
float nota[alunos];
char nome[15];

for(x=0; x<alunos; x++){
    printf("Digite o nome do %d(o) aluno: ", x+1);
    scanf("%s", nome);

    printf("Digite a nota do aluno %s: ", nome);
    scanf("%f", &nota[x]);

    printf("\n");
}

}

    
asked by anonymous 24.09.2016 / 15:58

2 answers

1

The general rule is: do not try to do anything complicated with scanf.

The purpose of the scanf function is to work with structured data, usually read from a file.

To work with read-only data, you usually have to use a library, such as "ncurses" in Linux, or scan each line manually, which is labor-intensive.

I've never seen a "real-life" program that uses scanf, just in school examples and exercises. :)

Having said all this, you can do something, as in the example below, but I think it does not make up for the work, it will always end up being "half-mouth". :)

#include<stdio.h>
#include<string.h>

#define N_ALUNOS 3

static void ignoreRestOfLine(void)
{
   char c;
   while((c = getchar()) != '\n' && c != EOF)
        /* discard */ ;
}

int main()
{
   int i;
   float nota[N_ALUNOS];
   char nome[15];

   for (i = 0; i < N_ALUNOS; i++)
   {
      printf("Digite o nome do %d(o) aluno: ", i+1);
      scanf("%14[ .a-zA-Z]%*[^\n]\n", nome);

      printf("Digite a nota do aluno %s: ", nome);
      scanf("%f", &nota[i]);
      ignoreRestOfLine();

      printf("\n");
   }

}
    
25.09.2016 / 05:55
1

You can use:

fgets (nome, 15, stdin); 

or you can use scanf even if you use a regex that will eliminate a space, because if you remember well scanf recognizes a space as a possible line break to end your reading, eg:

scanf ("%[^\n]%*c", nome);
    
24.09.2016 / 16:14