0

going straight to the problem here , i need to scan an imput of a sentence like : Name and Surname at once and it doesn't work properly tried scanf like shown in title and also fgets , at first it worked fine but once the code is a bit complex it jams ! am including a picture with the executed code

*// note this function is called by main(); tried writing the code in the main but the same
#include <stdio.h>
#include <string.h>
#include "Typedefs.h"


User Newuser;
log()
{

    printf("Name & Surname : ");
    fgets(Newuser.FullName,TAILLE_MAX,stdin);
    printf("Age : ");
    scanf("%d",&Newuser.age);
    printf("Matricule : ");
    scanf("%lld",&Newuser.MaT);

    printf("%s %d years \t Matricule : %lld",Newuser.FullName,Newuser.age,Newuser.MaT);
    fichier = fopen("userlog.txt","a+");
    if(fichier != NULL)
    {
        fprintf(fichier,"%s %d years \t Matricule : %lld",Newuser.FullName,Newuser.age,Newuser.MaT);

        fclose(fichier);
    }else
    {
        printf("error opening file!");
    }
}

this linked image shows the panel of code running

Fa Rouk
  • 1
  • 2
  • 2
    Please post the [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) with complete code that demonstrates the problem. The code is incomplete but I suspect from the output there is a menu selection using [`scanf()` which leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). BTW from the title it is a beginner's mistake to use `scanf("%[^\n]s")` which should be `scanf("%[^\n]")` or `scanf("%s")` but not both. They are different specifiers. – Weather Vane Oct 24 '20 at 15:50
  • indeed i use a menu with a simple printf and scanf then a switch to call my functions , thank you for your answers – Fa Rouk Oct 24 '20 at 15:56
  • 2
    To avoid mixing `scanf()` and `fgets()` you can input everything with `fgets()` and then apply `sscanf()` to the string. The added advantage is that when the input is badly formed (such as a word instead of a number) it makes it very easy to recover, whereas using `scanf()` some nasty kludge is needed to clear the unwanted input from the buffer. – Weather Vane Oct 24 '20 at 16:04
  • so if i don't want it to skip the next scanf() line i need to replace all of them with fgets() ? then how can i store in my int variables and the Name/Surname sentense ? – Fa Rouk Oct 24 '20 at 16:09
  • 1
    With `sscanf()`, as comments say. – Weather Vane Oct 24 '20 at 16:30

0 Answers0