Home > front end >  About entering a value with spaces for "scanf()"
About entering a value with spaces for "scanf()"

Time:12-24

I need help with my project homework The problem is, how can I enter a value with spaces using scanf() and gets()?

my code:

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

struct person {

    char *name_lastname[30];
    char *job[30];

};

int main()
{
int number;
printf("How many names will you enter? ");
scanf("%d", &number);

    struct person *people = (struct person*) malloc(number*sizeof(struct person));
    
    for(int i = 0; i<number; i  )
    {
        printf("name and last name: ");
        gets((people i)->name_lastname);
    
        printf("job: ");
        gets((people i)->job);
    }
    
    
    return 0;

}

I know there are similar answers here for this.

How do you allow spaces to be entered using scanf? "But we are not allowed to use fgets() in our assignment."

Or such uses solve my problem, I tried all of them. scanf("[0-9a-zA-Z ]", &number); scanf("[^\n]", &number);

As you can see, the functions I can use are very limited as it is a project assignment. strlen(), fgets() I am not allowed to use such functions.

My algorithm malfunctions when I enter a blank value without using scanf() and gets() .

CodePudding user response:

After much research, I solved the problem. Perhaps the compiler thinks that we have entered the value in another element for scanf() when we enter a blank value, or I understood it that way.

The resources below helped me a lot.

scanf(“%[^\n]s”, str) Vs gets(str) in C with Examples

What does scanf("%*[^\n]%*c") mean?

Algorithm working properly:

struct person {

    char name_lastname[30];
    char job[30];

};

int main()
{
int number;
printf("How many names will you enter? ");
scanf("%d", &number);

    struct person *people = (struct person*) malloc(number*sizeof(struct person));

    for(int i = 0; i<number; i  )
    {
        printf("name and last name: ");
        scanf(" %[^\n]", (people i)->name_lastname);

        printf("job: ");
        scanf(" %[^\n]", (people i)->name_lastname);
    }


    return 0;

}

Places I changed in my code: gets((people i)->name_lastname); ==> scanf(" %[^\n]", (people i)->name_lastname);

gets((people i)->job); ==> scanf(" %[^\n]", (people i)->job);

CodePudding user response:

typedef struct person {
char name_lastname[30];
char job[30];
} person;
char c;
...
fprintf(stdout,"print name and last_name:\n");
fscanf(stdout,"%s%[\n]%c",people[i].name_lastname,&c);
fprintf(stdout,"print occupation:\n");
fscanf(stdout,"%s%[\n]%c",people[i].job,&c);
....
  • Related