[英]How Terminate the Program on Pressing Enter key in C?
我正在制作一個小項目,我必須將不同的值轉換為不同的基數,如 10、8、16。等待輸入而不是簡單地終止。 我在在線編譯器上使用 C11 版本的 C。 這是我的代碼。
#include "ConvertInBackgnd"
#include<stdio.h>
int main() {
int choice;
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
l1: printf("Input your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
dec_bin();
break;
case 2:
bin_dec();
break;
case 3:
dec_octal();
break;
case 4:
octal_dec();
break;
case 5:
dec_hex();
break;
case 6:
goto l1;
default:
printf("Invalid choice.");
break;
}
printf("Input 6 for reconverting the values.");
scanf("%d", &choice);
if (choice == 6) {
goto l1;
} else
return 0;
return 0;
}
我制作了一個單獨的文件,我在其中制作了函數,我認為沒有必要也把代碼放在這里。
考慮使用fgets
將輸入輸入到字符數組中。
如果需要,可以使用sscanf
、 strtol
或其他方法解析輸入。
#include<stdio.h>
int main() {
char line[100] = "";
do {
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
printf("Input your choice : ");
fgets ( line, sizeof line, stdin);
switch ( line[0]) {
case '1':
printf ( "dec_bin()\n");
break;
case '2':
printf ( "bin_dec()\n");
break;
case '3':
printf ( "dec_octal()\n");
break;
case '4':
printf ( "octal_dec()\n");
break;
case '5':
printf ( "dec_hex()\n");
break;
case '6':
case '\n':
break;
default:
printf("Invalid choice.");
break;
}
if ( line[0] != '\n') {
printf("Input 6 for reconverting the values.");
fgets ( line, sizeof line, stdin);
}
} while ( line[0] == '6');
return 0;
}
解決輸入問題:
scanf("%d", &choice)
現在您正在獲取 int 值,嘗試使用 char 值並將輸入鍵與其匹配。 然后你就可以做你想做的事情了。
好的,所以如果按下 Enter 鍵,我想終止程序。 所以我首先是一個新手,然后我意識到這沒什么大不了的,為此我只需要將一個char
作為輸入,然后檢查該char
輸入是否為輸入鍵。 它是按回車鍵后終止程序的示例代碼。
char line;
scanf("%c",&line);
if(line=='\n')
return 0;
else
// your other code
但是如果你的程序不接受輸入,那么你應該在上面提供的代碼之前通過在上面的代碼之前添加這一行來清除緩沖區。
while(getchar()!='\n');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.