我正在嘗試使我的代碼...
我以為會這么簡單,但不幸的是,事實并非如此。
我該怎么做?
#include <stdio.h>
int main(void)
{
char y;
printf("Single provider (y/n)? ");
scanf(" %c", &y);
if (y == '121' || y == '89')
{
printf("single");
}
else
{
printf("not single");
}
}
uj5u.com熱心網友回復:
你在這里做了一個漂亮的混淆:顯然已經聽說過 ASCII 代碼,你想將它們應用到你的代碼中。這個想法是好的,而不是實作:
你的代碼:
if (y == '121' || y == '89')
正確代碼(無 ASCII 代碼):
if (y == 'y' || y == 'Y')
正確代碼(使用 ASCII 代碼):
if (y == 121 || y == 89) // ASCII_Code('Y')=89 and ASCII('y')=121
(請不要洗掉評論,這對可讀性非常有用)
祝你好運
uj5u.com熱心網友回復:
我應該怎么做才能在 C 中提出是或否的問題
有5個輸入集來區分:
"Y\n"
或類似的東西:"y\n"
,"Yes\n"
,"YES\n"
..."N\n"
或類似的東西:"n\n"
,"no\n"
, ...出現檔案結束。
scanf()
回傳EOF
并且feof(stdin)
為真。出現輸入錯誤。
scanf()
回傳EOF
并且ferror(stdin)
為真。(稀有的)別的東西。通常是用戶錯誤。
一般來說,最好避免scanf()
使用fgets()
。
然而堅持scanf()
:
讀入一行輸入。使用空格來消耗前導空格,包括前一行的'\n'
.
unsigned char buf[80];
buf[0] = 0;
int retval = scanf(" y[^\n]", buf);
然后消歧義。建議不區分大小寫。也許只允許第一個字母或整個單詞。
if (retval == EOF) {
if (feof(stdin) {
puts("End-of-file");
} else { // Input error expected
puts("Input error");
}
} else {
for (unsigned char *s = buf; *s; s ) {
*s = tolower(*s);
}
if (strcmp(buf, "y") == 0 || strcmp(buf, "yes") == 0) {
puts("Yes");
} else if (strcmp(buf, "n") == 0 || strcmp(buf, "no") == 0) {
puts("No");
} else {
puts("Non- yes/no input");
}
}
一個幫助函式來處理是/否,真/假,......怎么樣?
// Return first character on match
// Return 0 on no match
// Return EOF on end-of-file or input error
int Get1of2(const char *prompt, const char *answer1, const char *answer2) {
if (prompt) {
fputs(prompt, stdout);
}
unsigned char buf[80];
buf[0] = 0;
int retval = scanf(" y[^\n]", buf);
if (retval == EOF) {
return EOF;
}
for (unsigned char *s = buf; *s; s ) {
*s = tolower(*s);
}
if ((buf[0] == answer1[0] && buf[1] == 0) ||
strcmp(buf, answer1) == 0) {
return buf[0];
}
if ((buf[0] == answer2[0] && buf[1] == 0) ||
strcmp(buf, answer2) == 0) {
return buf[0];
}
return 0; // None of the above.
}
示例呼叫:
int yn = Get1of2("Single provider (y/n)? ", "yes", "no");
int rb = Get1of2("What is your favorite color? (r/b)? ", "red", "blue");
int tf = Get1of2("Nineveh the capital of Assyria? (t/f)? ", "true", "false");
uj5u.com熱心網友回復:
int main(void)
{
int y;
printf("Single provider (y/n)? ");
do
{
y = fgetc(stdin);
}while(y != EOF && y != 'y' && y != 'n');
if(y != EOF)
if (y == 'y')
{
printf("single");
}
else
{
printf("not single");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507341.html