从之前的帖子中,我知道您可以使用此处所示的方法来实现此目的:How do you allow spaces to be entered using scanf?
它在 Main 中工作,但是当我将它放入函数中时,它不起作用。
这是我的代码:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void dataInput();
struct record {
char title[50];
char author[50];
char category[20];
float price;
};
struct record info[500];
void main(){
dataInput();
}
void dataInput(){
int x;
for(x = 0; x <= 10; x++ ){
scanf("%s", &info[x].title);
printf("%s\n", &info[x].title);
}
}
输出:
如果我使用正则表达式:
scanf("%50[0-9a-zA-Z ]s", &info[x].title);
输出:
嗯,这里出了什么问题
最佳答案
我还没有手写最可靠的引用手册,但是来自 Wikipedia :
%s : Scan a character string. The scan terminates at whitespace. A null character is stored at the end of the string, which means that the buffer supplied must be at least one character longer than the specified input length.
因此,%s
在 scanf
和 printf
中执行非常不同的操作,并且将实际上只读取一个scanf
中的单词,而在 printf
中它将产生指向的空终止内容。
关于c - scanf 函数内的空白 - C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23989680/