为什么我输入句子跳过其他scanf
如果我为任何char scanf
打开输入类似“asdasd asd asdas sad”的句子,它将跳过其他scanfs。
如果我输入obligation
scanf this sentence
,它将写入obligation scanf
这个和下一个scanf将被跳过,但自动将是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
在遇到空白字符 (空格,换行符等)时停止扫描。 请改用%[
格式说明符:
scanf(" %[^\n]", obligation); scanf(" %[^\n]", dodatno);
%[^\n]
告诉scanf
扫描所有内容,直到换行符。 最好使用长度修饰符来限制要读取的字符数:
scanf(" %1499[^\n]", obligation); scanf(" %1499[^\n]", dodatno);
在这种情况下,它将扫描最多1499个字符(结尾处的NUL终止符为+1)。 这可以防止缓冲区溢出 。 您还可以检查scanf
的返回值,如@EdHeal 在注释中建议检查它是否成功。
我建议逐字逐句阅读。 你可以使用以下function,例如
//reads user input to an array void readString(char *array, char * prompt, int size) { printf("%s", prompt); char c; int count=0; while ( getchar() != '\n' ); while ((c = getchar()) != '\n') { array[count] = c; count++; if (size < count){ break; } //lets u reserve the last index for '\0' } } //in your main you can simply call this as readString(obligation, "Enter obligation", 1500);
每次连续调用scanf()都可以在格式字符串中有一个前导空格。
当格式字符串包含空格时,将消耗输入中任何“空格”,该空格位于输入中。
这包括制表符,空格,换行符。