简体   繁体   中英

scanf(“%[^\n]s”) works fine with normal variable but doesn't work with a structure variable in C

I am using GCC compiler

I wanted to scan white character as well so I used scanf("%[^\\n]s",&name) and it just worked fine.

say the code is

void main(){
    char name[20];
    scanf("%[^\n]s",&name);
    printf("%s",name);
}

but when i tried to use it with a structure variable the statement doesnt work anymore.

struct book { char name[20];};
main(){
    struct book buk[10];
    int i;
    for(i=0;i<3;i++)
    {
        printf("Enter name of book %d",i+1);
        scanf("%[^\n]s",&buk[i].name);}
    }

The scanf statement just don't execute.

But if I use simple scanf("%s",&name); it works just fine. Can someone please help me with this?

I used scanf("%[^\\n]s",&name) and it just worked fine ? No, it doesn't work fine. Read the manual page of scanf() it says

int scanf(const char *format, ...);

first argument is of char* type but &name is not of char* type.

This

char name[20]; 
scanf("%[^\n]s",&name);

Should be

scanf("%[^\n]",name);/* & is not needed as name itself address */

Also it should be just "%[^\\n]" not "%[^\\n]s" . Correct one is

scanf(" %19[^\n]",name); /* giving space before % prevents reading extra characters */

Also it's better to use fgets() . For eg

 char *p = fgets(buk[i].name),sizeof(buk[i].name),stdin);
 if(p != NULL) {
      /* do some stuff */
 }

Side note, if you are using fgets() then you should be aware of the fact that fgets() store \\n at the end of buffer. so you may want to replace that \\n with \\0 , for that you can use strcspn() or do it manually.

Edit : Note that stdin stream is line buffered ie after scanf("%[^\\n]",name); new line character \\n stays in stdin stream and if you are scanning data again second time, it may fail by not storing anything in name and may invokes undefined behavior. So first and foremost check the return value of scanf() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM