c - C语言任务提醒程序

标签 c string scanf

我正在用 c 语言编写一个简单的任务提醒程序,它会在一定时间后打印给定的任务。这是我遇到问题的一小部分代码。基本上我在使用 scanf() 时遇到了麻烦,因为该函数的行为很奇怪。

#include <stdio.h>
#include <time.h>

int main(){
   int hour,minute,curr_time,end_time;
   printf("input the hour and minute after which alarm will start in HH:MM : \n");
   scanf("%d:%d", &hour,&minute);
   char task[50];
   printf("Name of the task: \n");
   scanf("%s" , task);
   printf("your task is %s" , task);

return 0;
}

现在,当我编译并运行该程序时,会发生以下情况。

~$ ./a.out
input the hour and minute after which alarm will start in HH:MM : 
00.56
Name of the task: 
your task is .56

我无法输入任务名称。一旦我给出小时和分钟,程序就会结束,而不接受任务输入。

最佳答案

您在 scanf 中使用 : 作为分隔符,但在输入时输入了小数。由于 scanf 需要整数,因此它会在第一个小数点处停止扫描。

您可以通过打印来查看小时分钟的值

#include <stdio.h>
#include <time.h>

int main(){
   int hour,minute,curr_time,end_time;
   printf("input the hour and minute after which alarm will start in HH:MM : \n");
   scanf("%d:%d", &hour,&minute);
   char task[50];
   printf("Name of the task: \n");
   scanf("%s" , task);
   printf("your task is %s" , task);
   printf("hour is %d" , hour);
   printf("minute is %d" , minute);

return 0;
}

输出:

input the hour and minute after which alarm will start in HH:MM : 
00.56
Name of the task: 
your task is .56
hour is 0
minute is 0

scanf 中的分隔符更改为小数,或输入小时和分钟 00:56

input the hour and minute after which alarm will start in HH:MM : 
00:56
Name of the task: 
test
your task is test
hour is 0
minute is 56

关于c - C语言任务提醒程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33417804/

相关文章:

python - 初学者Python : Accumulator loop function

c - 如何使用 scanf() 在 C 中接受 char *

c - 另一个malloc.c :3096: sYSMALLOc issue with pthreads and mqueue

c - 将 ZMQ 上下文从 C 传递到嵌入式 Lua

c++ - 比较两个 C++ 十六进制字符串

java - Android:数组索引越界错误

c - 为什么此 scanf 语句会导致段错误?

c - 关于 scanf() 的奇怪跳过

c - 为什么 -fpie 在裸机代码中不起作用并导致野指针?

c - 使用 eclipse 和 cygwin 调试 C