scanf无法接收输入排查:军事时间格式输入至结构体需求
军事时间输入问题排查与实现方案
问题描述
需要接收hh:mm:ss格式的军事时间输入,将时、分、秒存入结构体。当前存在两个问题:
- 原代码中
scanf完全无法接收输入,刷新缓冲区无效 - 不清楚如何用
std::cin实现该格式输入,且不允许使用其他标准库函数
原代码
#include <iostream> using std::cout; using std::cin; struct MyTime {int hours, minutes, seconds;}; //using namespace std; MyTime *DetermineElapsedTime(const MyTime *start, const MyTime *stop); int main() { // declare start/stop/result structs MyTime start, stop, *result; // prompt user for start and stop times in military format cout << "Enter start time in military format: \n"; scanf("%2d%*c%2d%*c%2d\n", &start.hours, &start.minutes, &start.seconds); cout << "\n"; cout << "start hours is " << start.hours; cout << "start minutes is " << start.minutes; cout << "start seconds is " << start.seconds; //cout << "Enter stop time in military format: "; //scanf("%2d%*c%2d%*c%2d", &stop.hours, &stop.minutes, &stop.seconds); //cout << "stop hours is " << stop.hours; //cout << "stop minutes is " << stop.minutes; //cout << "stop seconds is " << stop.seconds; //result = DetermineElapsedTime(&start, &stop); //printf("%2d:%2d:%2d\n", result->hours, result->minutes, result->seconds); }
解决方案
1. scanf无法接收输入的修复
问题出在scanf格式串末尾的\n:scanf遇到格式串中的空白字符(包括\n)时,会持续读取输入中的空白字符,直到遇到非空白字符才会结束输入流程,导致程序一直卡住等待输入。
修改后的scanf语句:
scanf("%2d%*c%2d%*c%2d", &start.hours, &start.minutes, &start.seconds);
%2d:读取最多2位整数,匹配时、分、秒%*c:读取并忽略一个字符(用于跳过分隔的冒号:)- 移除末尾的
\n后,scanf读取完三个整数后立即返回,不会额外等待空白字符
2. 用std::cin实现hh:mm:ss格式输入
有两种简洁的实现方式,均无需额外标准库函数:
方式一:逐段读取+忽略冒号
cout << "Enter start time in military format: \n"; cin >> start.hours; cin.ignore(); // 跳过第一个冒号 cin >> start.minutes; cin.ignore(); // 跳过第二个冒号 cin >> start.seconds;
cin.ignore()会跳过输入流中的一个字符,正好处理分隔的冒号。
方式二:链式读取接收冒号
char colon; cout << "Enter start time in military format: \n"; cin >> start.hours >> colon >> start.minutes >> colon >> start.seconds;
声明临时字符变量colon来接收输入中的冒号,通过链式调用一次性完成格式匹配读取。
内容的提问来源于stack exchange,提问作者DOSHEA
相关产品推荐
相关产品推荐

