如果我为任何 char scanf
打开输入类似“asdasd asd asdas sad”的句子,它将跳过其他 scanfs。
例如,如果我键入 obligation
scanf this sentence
它将为 obligation scanf
编写 this and next scanf 将被跳过,但会自动be field with sentence word
...
代码如下:
while(cont == 1){
struct timeval tv;
char str[12];
struct tm *tm;
int days = 1;
char obligation[1500];
char dodatno[1500];
printf("Enter number of days till obligation: ");
scanf(" %d", &days);
printf("Enter obligation: ");
scanf(" %s", obligation);
printf("Sati: ");
scanf(" %s", dodatno);
if (gettimeofday(&tv, NULL) == -1)
return -1; /* error occurred */
tv.tv_sec += days * 24 * 3600; /* add 6 days converted to seconds */
tm = localtime(&tv.tv_sec);
/* Format as you want */
strftime(str, sizeof(str), "%d-%b-%Y", tm);
FILE * database;
database = fopen("database", "a+");
fprintf(database, "%s|%s|%s \n",str,obligation,dodatno);
fclose(database);
puts("To finish with adding enter 0 to continue press 1 \n");
scanf(" %d", &cont);
}
最佳答案
%s
在遇到 whitespace character 时停止扫描(空格,换行符等)。请改用 %[
格式说明符:
scanf(" %[^\n]", obligation);
scanf(" %[^\n]", dodatno);
%[^\n]
告诉 scanf
扫描所有内容,直到换行符。最好使用长度修饰符来限制要读取的字符数:
scanf(" %1499[^\n]", obligation);
scanf(" %1499[^\n]", dodatno);
在这种情况下,它将扫描最多 1499 个字符(最后的 NUL 终止符 +1)。这可以防止 buffer overruns .您还可以检查 scanf
的返回值为 @EdHeal suggests in a comment检查是否成功。
关于c - 为什么如果我输入句子其他 scanf 被跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31099508/