简体   繁体   中英

Reading spaces in C

I'm having a problem with my code: I have to write it to be able for the user to insert a description of a word. I'm writhing the code for a dictionary and here is the problem: when I start the program, the console reads only the first word and ignores the others. eg if I write "This means bla" it will read only "This".

I'm using this code:

char *Description;
scanf("%s", Description);
strcpy(word[i].description,Description);

.description is also a string in a structure were the the description have to be saved as well.

First up, you didn't allocate any memory to Description .

Second, scanf %s stops at blanks. You could use fgets instead:

fgets(word[i].description, LEN, stdin);

Or maybe:

scanf("%99[^\n]", word[i].description);

You cannot just read into a pointer, the pointer has to point first at writable memory. Of course you have an issue here of having no idea how much to allocate, but say we decide on 2048.

char Description[2048];
scanf( "%s", Description );

this will work as long as the string being typed in does not exceed 2047 characters. (It needs one more for the null terminator).

You might use gets instead of scanf, but you'd have a similar issue.

The safe one to use here is fgets

char Description[32]; // or whatever size you think is adequate
fgets( Description, sizeof(Description), stdin );

The number of characters will be limited. Note the null-terminator will be included for you so the maximum length of the string you receive will be 31 characters.

scanf is safer reading in numbers as those are fixed in size.

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