简体   繁体   English

在C中读取空格

[英]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". 例如,如果我写“ This means bla”,它将仅显示“ 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. .description也是结构中的字符串,必须同时保存描述。

First up, you didn't allocate any memory to Description . 首先,您没有为Description分配任何内存。

Second, scanf %s stops at blanks. 其次, scanf %s停在空白处。 You could use fgets instead: 您可以改用fgets

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. 当然,您这里的问题是不知道要分配多少,但是要说我们决定使用2048。

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

this will work as long as the string being typed in does not exceed 2047 characters. 只要输入的字符串不超过2047个字符,此命令都将起作用。 (It needs one more for the null terminator). (空终止符还需要一个)。

You might use gets instead of scanf, but you'd have a similar issue. 您可能会使用get而不是scanf,但是会遇到类似的问题。

The safe one to use here is fgets 在这里使用的安全的是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. 请注意,将为您包括空终止符,因此您接收到的字符串的最大长度为31个字符。

scanf is safer reading in numbers as those are fixed in size. scanf可以更安全地读取数字,因为它们的大小是固定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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