所以我制作了这个程序,它以以下格式询问用户时间:
HH:MM:SS
而且我已经把它的代码写下来了.. 除了一件事。假设用户输入如下内容:
12
此时,由于用户点击“输入”,我希望程序显示错误。
所以,这是我的问题:如果用户输入12:42141
(或其他类似的东西)我希望程序停止而不是让 scanf 等待 3 个整数。
我该如何编码?
无论如何,这是实际的程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define true 1
#define false 0
struct Time
{
int hours;
int minutes;
int seconds;
};
void AddOneSecond(struct Time *timePtr);
int CheckForErrors(struct Time timeVars, char charOne, char charTwo);
int main()
{
auto char firstColon;
auto char secondColon;
auto int secondsAdded;
auto int errorCheck;
struct Time userInput;
// Menu prompt
printf("Enter the start time in HH:MM:SS format: ");
scanf("%d %c %d %c %d", &userInput.hours
, &firstColon
, &userInput.minutes
, &secondColon
, &userInput.seconds);
// Check for errors
errorCheck = CheckForErrors(userInput, firstColon, secondColon);
// If the input format is correct, proceed with the program. If it's not,
// display an error message and terminate the program.
if (errorCheck)
{
printf("How many seconds would you like to add? ");
scanf("%d", &secondsAdded);
// Loop that calls the 'AddOneSecond' function 'secondsAdded' amount
// of times.
for (int i = 0; i < secondsAdded; i++)
{
AddOneSecond(&userInput);
printf("%02d:%02d:%02d \n", userInput.hours
, userInput.minutes
, userInput.seconds);
}
}
else
{
puts("Error reading input...");
return 0;
}
return 0;
}
void AddOneSecond(struct Time *timePtr)
{
timePtr->seconds++;
if (timePtr->seconds == 60)
{
timePtr->seconds = 00;
timePtr->minutes += 1;
}
if (timePtr->minutes == 60)
{
timePtr->minutes = 00;
timePtr->hours += 1;
}
}
int CheckForErrors(struct Time timeVars, char charOne, char charTwo)
{
auto int isInputValid = true;
if ((timeVars.hours < 0) || (timeVars.hours > 24))
{
isInputValid = false;
puts("The 'hours' value is invalid.");
}
if ((timeVars.minutes < 0) || (timeVars.minutes > 59))
{
isInputValid = false;
puts("The 'minutes' value is invalid.");
}
if ((timeVars.seconds < 0) || (timeVars.seconds > 59))
{
isInputValid = false;
puts("The 'seconds' value is invalid.");
}
if ((':' != charOne) || (':' != charTwo))
{
isInputValid = false;
puts("The 'colon' value is invalid.");
}
return isInputValid;
}