2016-11-10 25 views
1

我不知道爲什麼這段代碼不起作用。有人可以幫我嗎? (我想要一個簡單的版本,修復,如果有可能,因爲我纔開始學習下的幾個星期前。)如何比較C上的文字

#include <stdio.h> 
#include <string.h> 


int main() 
{ 
    char *name="alina"; 
    char *input; 
    printf ("what's your name? \n"); 
    scanf ("%s",&input); 
    if (input=="alina") 
     printf("your name is %s good job!\n ",&name); 
    if (input!="alina") 
     printf("are you sure? open the program again and insert the correct name"); 
    while (1); 
} 
+0

你需要爲輸入分配內存 - 看看malloc;比較字符串,你可以使用strcmp –

+0

這個思想。另外,在'input'和'name'之前去掉'&'。他們已經是指針了。 – itsme86

+0

你們中的一個人可以給我一個關於如何正確編寫代碼的例子嗎? –

回答

0

你做了一些錯誤。首先,如果你想插入一個字符串,你可以使用%s,但是你必須使用一個數組char,你可以在其中存儲該字符串。那就是,你必須寫這樣的東西。

char input[100]; 
scanf("%s", input); 

然後它會工作。這段代碼意味着:我需要插入(存儲)一個字符串。因此,首先我創建一個可以存儲它的地方(注意字符串最大爲99個字符;我的數組大小爲100,但最後一個字符用於表示字符串的末尾),然後使用scanf來寫我想要的。

第二個錯誤是,如果你想比較兩個字符串,你不能簡單地使用==!=,就像當你使用數字時一樣。該string.h庫,您可以使用strcmp功能,像這樣:

if (strcmp(name, input) == 0) // this means the strings are equal 
    ... 
else 
    ... 

記住

char* name = "Alina"; 
char input[100]; 

最終,在這裏你是你的代碼的檢查版本:

#include <stdio.h> 
#include <string.h> 

int main() { 

    char* name = "Alina"; 
    char input[100]; 
    printf("What's your name?\n"); 
    scanf("%s", input); 
    if (strcmp(name, input) == 0) 
     printf("Your name is %s good job!\n", name); 
    else 
     printf("Are you sure? Open the program again and insert the correct name\n"); 

    return 0; 
} 

的你的代碼的末尾是while(1)是絕對危險的,因爲它啓動了一個永無止境的無限循環,導致程序崩潰。你想要刪除它!

+0

非常感謝你!它終於工作了!關於while(1) - 當我不這樣做時,它立即關閉程序,但是當我寫它時,程序仍然是打開的,所以這就是我爲什麼這麼做的原因,但是再次非常感謝! –

+0

標記答案讓其他人知道它的工作 –

+1

無限循環不會使程序崩潰;它只是防止它終止,並在保持CPU運行平穩的情況下這樣做。很多人在IDE中編程,程序在終端窗口中運行,當程序退出時窗口消失使用「getchar()」的變體 - 通常是Windows上的「getch()」 - 等待來自用戶的輸入在退出之前。 –

1

需要辦理以下更改:

char input[256]; 
scanf("%s", input); 
printf("your name is %s good job!\n ", name); 

到比較字符串使用strcmp - 看看這個函數的文檔。

要小心scanf - 考慮可以存儲多長時間的字符串以及哪些地方可能出錯。看看scanf_s