CampbellMG
CampbellMG

Reputation: 2220

Unusual behaviour with scanf

I am trying to scan a string, it needs to have a max length of 10.

struct Person{
        char name[MAX];
        float score;
        date_t dafe;
    };

//MAX = 11

I am using a menu and when the string entered is less than 10 characters it works fine but when the string is longer it iterates through the menu and stores the rest of the string (anything past 10 characters) in the name value for the next student in the array (creating a new student). What am I doing wrong? Is this the correct way to limit a string with scanf?

while(choice != 6){
    printMenu();
    scanf("%d", &choice);
    switch(choice){
        case 1 : 
            if(Size < MAX){
                printf("Adding Person \n");
                personList[Size] = addPerson();
                Size++;
            }else{
                printf("Reached maximum size \n");
            }
            break;
        case 2 : //Other Options


Person_t addperson(void){
    person_t tempperson;

    printf("Enter name> \n");
    scanf("%10s", tempPerson.name);
    printf("Enter date: day> \n");
    scanf("%d", &person.date.day);
    //more values

    return tempPerson;
}

Upvotes: 1

Views: 81

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134346

What am I doing wrong?

In case your input is longer than the maximum field width, then, the excess entries present in the input buffer stays there to be read in the next call. So, after scanning, you need to clear off the input buffer off the remaining input before you proceed for the next input.

A rough way of achieving that would be while ('\n' != getchar()); but with this you'll have a problem for the cases where the input is <= 10 chars.

A better way is to read a whole line using fgets(), then use sscanf() to read-in the exact input you need.

Upvotes: 3

Related Questions