2016-01-20 137 views
1
#include <stdlib.h> 
#include <stdio.h> 

int main() 
{ 
    char word[100]; 

    while (word != "hello") { 

     system("clear"); 

     printf("\nSay hello to me : "); 

     scanf(" %s", word); 
    } 

    printf("congrats, you made it !"); 

    return 0; 
} 

在此代碼中:如果我輸入了任何內容,但是你好,循環繼續。但是,輸入ENTER鍵不會再循環,只會添加一行。在while循環中輸入鍵

我讀了一些使用getchar()可能會有所幫助的地方,但我對C開發有點新鮮,而且我在這裏搜索了幾個小時如何使它工作。

編輯0:

刪除

while (word != "hello") 
char word[100]; 
scanf(" %s", word); 

新增

#include <string.h> 
while (strcmp(word, "hello") != 0) 
char word[100] = {0}; 
fgets(word, 6, stdin); 

編輯1:

我想在我的代碼類似,包括那

fgets(word, 6, NULL); 

但它給我一個分段錯誤。

**編輯2:**

正確的工作輸入:

fgets(word, 6, stdin); 

所以它的工作,但增加超過6個字符的問題,如:

Say hello to me : hello from the inside 

將會打印:

Say hello to me : 
Say hello to me : 

所以我只是修改這樣的功能:

fgets(word, 100, stdin); 

但現在不會得到我任何輸入工作

+0

每行樣式的一行再次:)我想知道它從哪裏來,如果它是如此醜陋? –

+0

它看起來不像這個代碼將任何東西放入「單詞」中。你的scanf不應該使用word而不是mot嗎? mot也沒有定義。 – bruceg

+0

scanf希望閱讀leas中的一個非空白字符。 – nsilent22

回答

0

@dbush以及回答OP最初的擔憂。

OP現在在ħË升升ö輸入使用fgets(word, 100, stdin);和類型。 word[]然後用"hello\n"填充,並且不通過strcmp(word, "hello") != 0

解決方案:strip final '\n'

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#define BUFFER_SIZE 100 

int main() { 
    char word[BUFFER_SIZE] = { 0 }; 

    while (strcmp(word, "hello") != 0) { 
    system("clear"); 
    printf("\nSay hello to me : "); 
    // insure buffered output is flushed 
    fflush(stdout); 

    // Avoid magic numbers, use `sizeof word` 
    // Test if input was received 
    if (fgets(word, sizeof word, stdin) == NULL) { 
     fprintf(stderr, "\nInput closed\n"); 
     return 1; 
    } 

    // lop off potential trailing \n 
    word[strcspn(word, "\n")] = '\0'; 
    } 

    printf("congrats, you made it !\n"); 
    return 0; 
} 
3

三兩件事:

你並不需要在scanf格式的空間串。 %s格式說明符已經忽略了前導空格。因此,而不是" %s"使用"%s"

主要問題是word != "hello"。這不是如何比較字符串。你實際做的是將word的地址與字符串常量"hello"的地址進行比較。要進行字符串比較,請使用strcmp。如果返回0,字符串是一樣的,所以你的while循環還應當檢查非零:

while (strcmp(word,"hello")) { 

一定要#include <string.h>得到的strcmp聲明。

最後,你需要初始化word,使初始字符串比較不通過讀取未初始化的數據調用未定義行爲:

char word[100] = {0}; 
+0

scanf是一個壞主意,爲交互式會話,你想讀一條線 –

+0

感謝我做筆記,其實我正在衝進那個關鍵問題,所以我忘了我所有的禮儀:) –