一個(gè)非常簡(jiǎn)單的問(wèn)題。為什么在第一個(gè)while循環(huán)中跳過(guò)scanf。我已經(jīng)嘗試過(guò)使用getchar(),結(jié)果是一樣的。getchar被跳過(guò)。如果你們不明白我在說(shuō)什么,您可以嘗試編譯它,你們會(huì)明白我在問(wèn)什么。#include <stdio.h>#include <string.h>#include <stdlib.h>typedef struct rec{ int num; char pref[16]; float point; struct rec* next;}rec;void dataInput(float*,char*);rec* insertNode(rec*);int main(){ int i=1; rec* entr,*pt = NULL; entr = (rec*) malloc(sizeof(rec)); entr->num = i; dataInput(&entr->point,entr->pref); entr->next = NULL; char key; i++; while(1){ printf("Continue ? If YES press 'y',or NO press 'n'\n"); key = getchar(); if(key == 'n')break; else if(key == 'y'){ if(!pt){ pt = insertNode(entr); }else{ pt = insertNode(pt); } dataInput(&pt->point,pt->pref); pt->num = i; i++; continue; }else{ printf("Wrong key! Please Press again! \n"); } } pt = entr; while(pt){ printf("num : %d, pref : %s, point: %.1f\n", pt->num, pt->pref, pt->point); pt = pt->next; } getchar(); getchar(); return 0;}void dataInput(float* point,char* pref){ printf("Input Point\t : "); scanf("%f",point); printf("Input Pref\t : "); scanf("%s",pref);}rec* insertNode(rec* current){ rec* newnode = (rec*)malloc(sizeof(rec)); current->next = newnode; newnode->next = NULL; return newnode;}
3 回答

慕標(biāo)5832272
TA貢獻(xiàn)1966條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是因?yàn)?code>scanf將'\n'
在輸入緩沖區(qū)中留下一個(gè)(結(jié)束符)符號(hào)。該符號(hào)將getchar
在此while(1)
循環(huán)的第一次迭代中被消耗。

BIG陽(yáng)
TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
getchar() 在輸入緩沖區(qū)中留下?lián)Q行符,隨后的scanf()會(huì)讀取該換行符。
您可以通過(guò)在scanf中使用前導(dǎo)空格來(lái)解決此問(wèn)題:
scanf(" %c ...", &c,..);
告訴scanf忽略所有空白字符?;蛘遟etchar()在第一個(gè)getchar()之后使用另一個(gè)權(quán)利來(lái)使用換行符。
- 3 回答
- 0 關(guān)注
- 753 瀏覽
添加回答
舉報(bào)
0/150
提交
取消