解決C語言輸入單個(gè)字符屏蔽回車符的問題
C語言的scanf()函數(shù)在接收輸入單個(gè)字符時(shí)會(huì)把上一次輸入的回車符號(hào)當(dāng)做這次輸入的字符,造成無法正確的輸入字符數(shù)據(jù)。這恐怕是初學(xué)C的童鞋門遇到的最頭疼的問題了。
今天給大家提供四種解決方法供借鑒。
1、在scanf()中使用'\n'屏蔽回車符號(hào)。
scanf("%d\n",&n); //使用'\n'過濾回車
scanf("%c",&c);
2、在scanf()格式串最前面添加空格,屏蔽回車字符
scanf("%d",&n);
scanf(" %c",&c); //%c前面加空格,過濾回車
3、在接收字符前,使用getchar()來讀取一次回車符號(hào)
scanf("%d",&n);
getchar(); //專門用來讀取上次輸入的回車符號(hào)
scanf("%c",&c);
4、在接收字符前,使用fflush()清空輸入流中緩沖區(qū)中的內(nèi)容
scanf("%d",&n)
fflush(stdin); //清空輸入流緩沖區(qū)的字符,注意必須引入#include <stdlib.h>頭文件
scanf("%c",&c);
好了,以后再也不用為這個(gè)問題煩惱了.....
補(bǔ)充知識(shí):C語言中使用scanf()對(duì)字符(串)進(jìn)行輸入的問題
1. 輸入字符串
#include<stdio.h>
int main() {
int a;
char s1[100];
char s2[100];
scanf("%d", &a);
scanf("%s", s1);
scanf("%s", s2);
printf("a = %d\n", a);
printf("s1 = %s\n", s1);
printf("s2 = %s\n", s2);
return 0;
}
輸入
2019 hello world
輸出
a = 2019 s1 = hello s2 = world
沒有問題,因?yàn)閟canf("%s")遇到換行符會(huì)自動(dòng)跳過
2.輸入字符
#include<stdio.h>
int main() {
int a;
char s1;
char s2;
scanf("%d", &a);
scanf("%c", &s1);
scanf("%c", &s2);
printf("a = %d\n", a);
printf("s1 = %c\n", s1);
printf("s2 = %c\n", s2);
return 0;
}
輸入
2019 A B
輸出
a = 2019 s1 = s2 = A
可以看到s1將2019后面的回車符'\n'吸收了,原因是scanf("%c")在讀取單個(gè)字符時(shí),空格和回車都被視為單個(gè)字符。
解決辦法
使用getchar()吸收掉多余的回車
#include<stdio.h>
int main() {
int a;
char s1;
char s2;
scanf("%d", &a);
getchar(); // 吸收"\n"
scanf("%c", &s1);
getchar(); // 吸收"\n"
scanf("%c", &s2);
printf("a = %d\n", a);
printf("s1 = %c\n", s1);
printf("s2 = %c\n", s2);
return 0;
}
在格式串中過濾掉回車
#include<stdio.h>
int main() {
int a;
char s1;
char s2;
scanf("%d\n", &a); // 過濾掉回車
scanf("%c\n", &s1);
scanf("%c", &s2);
printf("a = %d\n", a);
printf("s1 = %c\n", s1);
printf("s2 = %c\n", s2);
return 0;
}
以上這篇解決C語言輸入單個(gè)字符屏蔽回車符的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
C語言?使用qsort函數(shù)來進(jìn)行快速排序
排序方法有很多種:選擇排序,冒泡排序,歸并排序,快速排序等。?看名字都知道快速排序是目前公認(rèn)的一種比較好的排序算法。因?yàn)樗俣群芸欤韵到y(tǒng)也在庫里實(shí)現(xiàn)這個(gè)算法,便于我們的使用。?這就是qsort函數(shù)2022-02-02
先序遍歷二叉樹的遞歸實(shí)現(xiàn)與非遞歸實(shí)現(xiàn)深入解析
以下是對(duì)先序遍歷二叉樹的遞歸實(shí)現(xiàn)與非遞歸實(shí)現(xiàn)進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過來參考下2013-07-07
C語言菜鳥基礎(chǔ)教程之單精度浮點(diǎn)數(shù)與雙精度浮點(diǎn)數(shù)
在C語言中,單精度浮點(diǎn)數(shù)(float)和雙精度浮點(diǎn)數(shù)(double)類型都是用來儲(chǔ)存實(shí)數(shù)的,雙精度是用記憶較多,有效數(shù)字較多,數(shù)值范圍較大。2017-10-10
C++宏函數(shù)和內(nèi)聯(lián)函數(shù)的使用
本文主要介紹了C++宏函數(shù)和內(nèi)聯(lián)函數(shù)的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07

