【问题标题】:task reminder program in cc中的任务提醒程序
【发布时间】:2015-10-29 15:04:11
【问题描述】:

我正在用 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

我无法输入任务的名称。一旦我完成了 hour 和 minute ,程序就会结束而不接受任务输入。

【问题讨论】:

  • 当我按照提示输入时间时,我的编译(MSVC)运行良好。 %s 格式规范忽略了空格,所以 scanf 功能不满足只要我一直按“Enter”,我必须输入一些文本,在第一个 space 字符处被截断。

标签: c string scanf


【解决方案1】:

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

打印hoursminutes 可以看到它们的值是什么

#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

【讨论】:

  • 我一直将小时和分钟输入为 HH:MM ,似乎程序在前 15 分钟没有响应,现在一切正常。够奇怪的!
  • @JosephQuinsey 谢谢!
【解决方案2】:

考虑使用 FGET 代替 scanf。现在,在您输入时间后,您将在缓冲区中留下一个换行符。当 scanf 读取字符串时,它会抓取换行符。让它看起来好像跳过了你的输入。

【讨论】:

  • 当以正确的 HH:MM 格式输入时间时,程序运行良好。 %s 格式不会“抓取换行符”,实际上它拒绝接受 newline
【解决方案3】:

你的代码只有一个粗心的错误。那就是scanf中没有&符号

& 在 scanf 中有特殊的作用。它表示需要存储值的地址。

但是,这个没有显示任何错误

由于这个原因,您会得到一个输出作为您最后输入的值,直到达到换行符,即 .56

请注意,在某些情况下,它会导致整个程序出现故障。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    相关资源
    最近更新 更多