C Program yes no 問題..

char response;

printf("\nDo you want to create a new database? (y/n)");
scanf("%s", &response);

if (response == 'Y'){
printf("\nYou want to create new database!\n");
}
else if (response == 'N')
{
printf("\nYou selected, no!\n");
}

run program無問題, 但係一打完Y/N就會彈個視窗出ERROR..有無人知我錯左咩?

Thanks !!

Use %c instead of %s

TOP

用scanf("%c", &response);
string有NULL CHAR '\0', 一個char入唔到兩個character,只係睇一個char就用%c
http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

TOP

唔該曬兩位!但而家又有新問題啦, 我轉左%c 果陣, 未打y/n 已經彈左個error視窗出黎
  1. printf("\nDo you want to create a new database? (y/n)");
  2.         scanf("%c", &response);

  3.         if (response == 'Y'){
  4.         printf("\nYou want to create new database!\n");
  5.         }
  6.         else if (response == 'N')
  7.         {
  8.     mysql_query(conn,"show databases");
  9.     result = mysql_store_result(conn);
  10.     i=0;

  11.         }
複製代碼

TOP

會否是前面的code造成的?看這一部份應該ok啊~

TOP

本帖最後由 gilbertluis 於 2010-3-5 15:24 編輯

If you think crash in scanf, replace
scanf("%c", &response);
with
response = getc( stdin );

I think scanf should be ok. It is most likely response is neither 'Y' or 'N' (such as \r ,\n, 'y' or 'n') and your program continued to run after the code segment given.

TOP

但樓主說: 未打y/n 已經彈左個error視窗出黎,所應該未有任何輸入,對嗎?

TOP

本帖最後由 gilbertluis 於 2010-3-8 18:55 編輯

see the screen shot, previous input is asking password. '\n' may be remaining in the stdin stream for scanf("%c" ,... ) to get.

change to scanf( " %c", &response); in such case.

TOP

scanf() may pick up the keystrokes left over from the previous scanf(), for example, the "enter" key.  And since u are using "%c", these leading "whitespace" characters are not skipped.  Hence, ur variable "response" may be assigned the "enter' char you previously pressed.   Try to initialize "response" before that scanf() call, and then check both the return value of scanf() and ur "response" afterwards.

In contrast, "%1s" skips the leading whitespace characters from the input.

TOP

唔該曬大家!我仲未試, 有時間會再試的

TOP