![](/img/trans.png)
[英]A simple C program to reverse every line of input. I have finished it. But I keep getting �$
[英]simple input. program crashes
#include <stdio.h>
#include <string.h>
int main(){
char *command="0";
do {
printf("[A]dd, [P]rint, [Q]uit\n");
scanf("%s", command);
while (strcmp(command, "a") != 0 && strcmp(command, "A") != 0 && strcmp(command, "p") != 0 && strcmp(command, "P") != 0){
printf("Invalid input. Please enter one of the commands listed above.\n");
scanf("%s", command);
}
if (strcmp(command, "a") == 0 || strcmp(command, "A") == 0){
printf("You selected add.\n");
}
else if (strcmp(command, "p") == 0 || strcmp(command, "P") == 0){
printf("You selected print.\n");
}
}while (strcmp(command, "q") != 0 && strcmp(command, "Q")!= 0);
return 0;
}
我希望程序從開頭打印的指定命令之一接收用戶的來信。 我希望程序在輸入q或Q時退出。花了我一段時間,以弄清楚如何對循環和ifs的字符串進行比較。 現在,當我運行程序時,它雖然崩潰了。 尋找有關其崩潰原因的見解。
是的,將您的buffer command
放入常規數組中,並將其增大:
char command[256];
無需初始化它, scanf
會解決這個問題。 另外,它不會影響崩潰,但是如果您只檢查一個字母,則可以這樣操作:
if command[0] != 'a' && command[0] != 'A' (etc.)
請注意單引號:這是一個字符比較。
char *command="0";
scanf("%s", command);
您正在寫入字符串文字(僅2個字節),並且字符串文字不需要進行修改。
使用類似這樣的東西:
char command[256];
scanf("%s", command);
或更好地使用fgets
+ sscanf
以避免潛在的緩沖區溢出。
這是指向只讀存儲器的指針:
char *command="0";
這意味着這是錯誤的:
scanf("%s", command);
“快速破解”是一種糟糕的做法,它更改了命令的定義,因此它獲得了一些讀寫內存而不是只讀內存:
char command[256] = "0";
但這仍然使您處於緩沖區溢出的嚴重危險中。 不要使用scanf
。
“更好的方法”是使用fgets
而不是scanf
:
char command[256];
char *p;
p = fgets(command, sizeof(command), stdin);
if (!p) { handle error or EOF }
/* Don't forget that 'command' will probably have '\n' at the end,
you will have to strip it off */
好吧,突然出現在我scanf
是,您正在使用scanf
將數據讀取到只讀內存中,即字符串常量。 嘗試執行此操作時未定義,但是可能會導致程序崩潰。 您需要為command
分配一些讀/寫內存; 聲明為例如
char command[10];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.