getchar()的疑问

今晚打老虎 2009-03-10 10:47:14
这是C和指针第一章举的那个例子。其中的一部分我看不明白。大家帮我分析下
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define MAX_COLS 20
#define MAX_INPUT 1000

int
read_column_numbers(int columns[],int max);

void
rearrange(char *output,char const *input,int n_columns,int const columns[]);


int
main(void)
{
int n_columns;
int columns[MAX_COLS];
char input[MAX_INPUT];
char output[MAX_INPUT];

n_columns = read_column_numbers(columns,MAX_COLS);

while(gets(input)!=NULL){
printf("Original input : %s\n",input);
rearrange(output,input,n_columns,columns);
printf("Rearrange line %s\n",output);
}
return EXIT_SUCCESS;


system("PAUSE");
return 0;
}

int
read_column_numbers(int columns[],int max){
int num=0;
int ch;

while(num<max&&scanf("%d",&columns[num])==1&&columns[num]>=0)
num+=1;
if(num%2!=0){
puts("Last column number is not paired.");
exit(EXIT_FAILURE);
}
while((ch=getchar())!=EOF&&ch!='\n')//这里getchar到底是要干什么呢?书上说是丢掉该行中包含最后一个数字的那部分内容。如果我的输入是4 9 12 20 -1,是不是-1要被丢弃?可是我检查变量,-1被存储到columns[4]里了。那这个语句又有什么用?
;
return num;
}

void
rearrange(char *output,char const *input,int n_columns,int const columns[]){
int col;
int output_col;
int len;

len=strlen(input);
output_col=0;

for(col=0;col<n_columns;col+=2){
int nchars=columns[col+1]-columns[col]+1;

if(columns[col]>=len||output_col==MAX_INPUT-1)
break;

if(output_col+nchars>MAX_INPUT-1)
nchars=MAX_INPUT-output_col-1;

strncpy(output+output_col,input+columns[col],nchars);
output_col+=nchars;
}
output[output_col]='\0';
}
...全文
141 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
今晚打老虎 2009-03-11
  • 打赏
  • 举报
回复
另外指出5楼的一处错误。
应该使用int类型变量接收getchar()的返回值
今晚打老虎 2009-03-11
  • 打赏
  • 举报
回复
谢谢楼上的各位^_^
看了你们的讲解,我的理解是:当我输入数据以后,在标准IO缓冲里会存储我输入的回车,用while((ch=getchar())!=EOF&&ch!='\n');//清空缓冲的回车,就能防止被误认为接下来的第一行输入数据。
这样看来书上说的/*丢弃该行中包含最后一个数字的那部分内容*/并不准确?因为输入4 9 12 0 -1回车以后。只有回车被清空了,-1仍然在数组里。

5楼的解答很详细。再次感谢
bo.cui 2009-03-11
  • 打赏
  • 举报
回复
.....
while((ch=getchar())!=EOF&&ch!='\n')
这种东西很常用~(当你不了解ffush()的时候)。
用来清空流缓冲区。防止污染下次输入~~

很简单的例子:
#include <stdio.h>

int main(void)
{
char ch;
getchar();//1处
getchar();//2处
return 0;
}
看似程序停止2次,等待输入2个字符。
但是,程序执行到1处,输入:a<回车>
a被读入,回车则存储进入标准IO缓冲。
程序执行到2处,此输入直接从缓存读取<回车>,不在等待用户输入,程序结束。

修改如下:
#include <stdio.h>

int main(void)
{
char ch;
getchar();
while((ch=getchar())!=EOF&&ch!='\n');//清空缓冲的回车
getchar();
return 0;
}
  • 打赏
  • 举报
回复
http://zhidao.baidu.com/question/9086712.html
你比较一下getch跟getchar的区别,就更清楚了.
Proteas 2009-03-10
  • 打赏
  • 举报
回复
同意楼上。
lingyin55 2009-03-10
  • 打赏
  • 举报
回复
while((ch=getchar())!=EOF&&ch!='\n')//判断是否读到一个换行符或者文件结束符EOF
sagegz 2009-03-10
  • 打赏
  • 举报
回复
getchar()获得单个字符.while判断是否输入结束.

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧