1
所以我做了這個程序,它要求用戶在以下格式的時間:
HH:MM:SS
我已經得到了它的代碼下來..除了一事情。 我們假設用戶輸入如下內容:
12
此時,由於用戶點擊'enter',我希望程序顯示錯誤。
所以,這是我的問題:如果用戶輸入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;
}
謝謝您的回覆!但我有個問題。這條線是如何工作的? '(str [0] - '0')* 10 +(str [1] - '0');' – relapsn
這會將字符串的小時部分轉換爲小時數的int值。例如,如果輸入12:32: 30,那麼'str [0]是'1'和'1' - '0'這將變成1'。 'str'[str] [0] - '0')* 10 +(str [1] - '0');'這個'str [1]'2'和'2' - '0'將變成2'將導致12 – Gangadhar
好的,'0'部分使它成爲'減'字符,這就是轉換髮生的地方? – relapsn