2014-08-31 45 views
0

嗨,這是我在這個網站上的第一篇文章,我剛開始學習C語言編程。我試圖尋找其他職位對我的具體問題,但其他答案的複雜性有點不知所措。 (所以我很抱歉,如果它是多餘的)雖然循環麻煩和重新分配在C(初學者)的字符變量

我想寫一個代碼,需要4個輸入數字,將它們打印回給你,然後問你是否想用y/n選項再次執行它。我需要一些幫助讓計算機讀取用戶的y/n輸入,然後繼續/打破基於此的循環。這是我到目前爲止,但我得到一些不好的錯誤,謝謝。

#include <stdio.h> 

int main() 
{ 
    int x[5]; 
    char choice; 

    choice = 'y'; //Assigned choice to y// 

    while (choice == 'y') 
    { 

     printf("Please input up to four numbers seperated for example, 1 2 3 4 : "); 

     scanf_s("%d %d %d %d", &x[0], &x[1], &x[2], &x[3]); 

     printf("Your entries in reverse order are %d %d %d %d\n", x[3], x[2], x[1], x[0]); //This is working// 

     printf("Would you like to enter another set of numbers? <y/n>:"); 

     scanf_s(" %c", choice); //Want this line to get an input y/n and if y, repeat the loop and if n, end the program// 

    } 

    printf("Goodbye\n"); 

    system("Pause"); 

    return 0 ; 
} 
+1

「壞的錯誤」 - 告訴我們它們是什麼。運行時錯誤或編譯器錯誤?編譯器消息是*診斷信息*因此,當要求某人診斷問題時,如果您提供該信息,則有助於(甚至是禮貌)。 – Clifford 2014-08-31 17:15:18

+2

與問題無關,但你可以在聲明中初始化'choice'而不是聲明然後賦值:'char choice ='y';' – Clifford 2014-08-31 17:20:48

+0

我建議在while循環中使用'do while'循環。那麼你不必在開始時設置「choice」的值。 – 2014-08-31 18:05:37

回答

2

您需要更改到scanf_s調用來獲取輸入第二次以下:

scanf_s(" %c", &choice, 1); 

注意,1,則意味着緩衝區的大小。

MSDN

In the case of characters, a single character may be read as follows: 

char c; 
scanf_s("%c", &c, 1); 
+0

謝謝修復它! – AlexT0311 2014-08-31 18:36:32

1

應該

scanf_s("%c", &choice, 1); 

scanf函數需要指針變量。否則scanf將無法爲「選擇」提供新的價值。 這是一個流行的錯誤。

編輯: 如果您搜索關於scanf_s的更多信息,您可以基於標準庫中的scanf。 012fScanf_s在功能上與scanf完全相同。 唯一的區別是scanf_s更安全,因爲它具有額外的參數來確定變量的大小。

0

首先學會縮進代碼,這樣可以提高很多可讀性。更改

scanf_s(" %c", choice); 

scanf(" %c", &choice); 

會從您的代碼中刪除所有的錯誤。

`