[英]Comparing strings and keyboard inputs
當我在鍵盤上輸入“quit”時,if 循環(由注釋“here quit is implemented”標記)應該返回 true,並且程序應該結束。 但 strcmp 不返回零。 沒有編譯器錯誤。 我無法確定問題所在。
int numInput(){
char str[10];
int num;
char nStr[10];
char q[4] = "quit"; //Quit
LAND:
scanf("%s",&str);
if (strcmp(q,str) == 0){ //Here quit is implemented
exit(0);
}else{
printf(str);
}
num = atoi(str);
itoa(num,nStr,10);
if (strcmp(nStr,str) != 0){
printf("Please enter numbers only!\nEnter number here:");
goto LAND;
}
return num;
}
char
數組q
沒有足夠的空間來存儲字符串"quit"
。
該字符串需要 5 個字符:4 個用於字母,1 個用於終止空字節。 而且由於數組不夠大,嘗試在其上使用字符串函數會導致這些函數讀取數組的末尾。 這會觸發未定義的行為。
數組需要至少大一個元素:
char q[5] = "quit";
甚至更好:
char q[] = "quit";
哪個大小的數組適合初始化程序。
此外,這是不正確的:
scanf("%s",&str);
當您傳遞一個指向數組的指針時, %s
格式說明符需要一個char *
。 這應該是:
scanf("%s",str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.