[英]Why does getchar() take two inputs when I only want one?
我試圖只讀取一個字符,但是我的循環繼續獲取輸入的鍵和 “ enter”鍵。 我如何避免這種情況發生,只抓住第一把鑰匙? 這是一個例子:
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
int rseed = 1448736593;
int main(int argc, char** argv) {
printf("#Program started successfully with random seed %i\n", rseed);
int c;
while(true) {
printf("input: ");
c = getchar();
printf("You selected %i\n", c);
}
return 0;
}
代碼是這樣的:
#Program started successfully with random seed 1448736593
input: 2
You selected 50
input: You selected 10
input: 3
You selected 51
input: You selected 10
input: 1
You selected 49
input: You selected 10
input: ^C
如何防止它也告訴我我選擇了10
? 我想將其保留給用戶僅單擊“ enter”(輸入),而別無其他。
您獲得的第二個值(換行符/換行符的10
十進制ASCII碼)是由於Enter鍵產生的換行符。
解決此問題的最簡單方法:
c = getchar();
if (c != '\n') // or (c != 10)
getchar(); // call again getchar() to consume the newline
printf("You selected %i\n", c);
現在的輸出是:
input: 2
You selected 50
input: 3
You selected 51
input: // <- Enter alone was pressed here
You selected 10
input: 1
You selected 49
input: ^C
但是,此處未處理用戶在按Enter鍵之前輸入多個字符的情況,在這種情況下,將忽略第二個字符。
char c = getchar();
當控件位於上方時,getchar()函數將接受單個字符。 接受字符控制后,保持在同一行。 當用戶按下Enter鍵時,getchar()函數將讀取該字符,並將該字符分配給變量'c'。
要忽略換行符:
int getchar2(void) {
int ret;
do {
ret = getchar();
} while (ret == '\n');
return ret;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.