雖然我可以確認我正在輸入正確類型的輸入到我的C程序中,但我無法正確解釋它的條件。當我運行以下代碼時,程序成功調用lengthFormula()
,然後打印"Choose from the following..."
輸入提示。C程序條件無法識別可操作的輸入
int main(void)
{
char newCalculation;
do
{
char newCalculation;
lengthFormula();
printf("\nChoose from the following:\n a.) Calculate the length of a multi-bar scene in this project\n b.) Calculate bar length for a NEW project\n c.) Exit\n\n");
scanf(" %c", &newCalculation);
/* printf("%c", newCalculation); */
}while(tolower(newCalculation) == 'b');
if(tolower(newCalculation) == 'a')
{
float barLength;
multiBar(barLength);
}
if(tolower(newCalculation) == 'c')
{
exitProgram();
}
return 0;
}
當我進入a
,而不是再次調用lengthFormula()
,main()
回報0
和程序終止。當我取消註釋第二個printf()調用並再次編譯/運行時,輸入a
返回a
,但它仍然返回0
/程序終止,而不是調用lengthFormula()
。
在@simplicisveritatis的建議,我也試着將我的條件語句,像這樣的主要do-while循環中,具有相同的結果:
int main(void)
{
char newCalculation;
do
{
char newCalculation;
lengthFormula();
printf("\nChoose from the following:\n a.) Calculate the length of a multi-bar scene in this project\n b.) Calculate bar length for a NEW project\n c.) Exit\n\n");
scanf(" %c", &newCalculation);
/* printf("%c", newCalculation); */
if(tolower(newCalculation) == 'a')
{
float barLength;
multiBar(barLength);
}
if(tolower(newCalculation) == 'c')
{
exitProgram();
}
}while(tolower(newCalculation) == 'b');
return 0;
}
我如何改變我的條件,使他們識別我的輸入?請不要告訴我使用getchar()
,因爲每次我這樣做,其他人都會告訴我使用scanf()
,其他人說這是危險的。我只是想了解爲什麼我的條件不起作用。
爲什麼他們告訴你使用'scanf()'?,請任何理由。你是否包含'stdio.h'和'ctype.h'?而這個「浮動槓」 multiBar(barLength);'是未定義的行爲,因爲你永遠不會初始化'barLength'。 –
我們知道,有關於如何從用戶獲得輸入的章節。人們鄙視scanf,但其他人使用它也一樣。一些人堅持cin >> v,其他人則警告說「這會給你一個字符串」......但是,您的scanf函數在上下文中是暫時的。 – JVene
'cin >> v'與這個問題無關,因爲這是[tag:c]而不是[tag:C++],並且是'scanf()'是可怕的。特別是因爲它沒有正確地在書本中出現,他們通常忽略它的返回價值。 –