随笔 - 251  文章 - 504  trackbacks - 0
<2010年11月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

本博客系个人收集材料及学习记录之用,各类“大侠”勿扰!

留言簿(14)

随笔分类

收藏夹

My Favorite Web Sites

名Bloger

非著名Bloger

搜索

  •  

积分与排名

  • 积分 - 197598
  • 排名 - 289

最新评论

 假如你的程序同时需要使用getchar()进行字符输入和使用 scanf()进行数字输入.这两个函数的每一个都能很好的完成工作,
但是它们不能很好地混合在一起.这是因为getchar()读取每个字符,包括空格,制表符和换行符;而scanf()在读取数字时候则
会跳过空格,制表符和换行符.下面是个例子,
char1.cpp
/*C语言一个I/O问题程序*/
#include<stdio.h>
void display(char cr,int lines,int width);
int main(void)
{
  int ch;
  int rows,cols;
  printf("Enter a character and tow integers:\n");
  while((ch=getchar())!='\n')
  {
     scanf("%d %d",&rows,&cols);
     display(ch,rows,cols);

     printf("Enter another character and tow integers;\n");
     printf("Enter a newline to quit.\n");
  }
  printf("Bye.\n");
  return 0;
}
void display(char cr,int lines,int width)
{
  int row ,col;
  for(row =1;row<=lines;row++)
  {
    for(col=1;col<=width;col++)
    {
      putchar(cr);
       }
      putchar('\n');

  }
}
结果输出:
Enter a character and tow integers:
d 3 2
dd
dd
dd
Enter another character and tow integers;
Enter a newline to quit.
Bye.
Press any key to continue...

 可以看见紧跟在2后面的那个换行符,scanf()函数将该换行符留在了输入队列中.而getchar()并不跳过换行符,所以在循环的
下一周期,在你有机会输入其他内容之前,这个换行符由getchar()读出,然后将其赋值给ch,而ch为换行符正是终止循环的条件.

 要解决这个问题,必须跳过一个输入周期中键入的最后一个数字与下一行开始处键入的字符之间的所有换行符或空格.
改进如下:char2.cpp

/*C语言一个I/O问题程序修改版本*/
#include<stdio.h>
void display(char cr,int lines,int width);
int main(void)
{
  int ch;
  int rows,cols;
  printf("Enter a character and tow integers:\n");
  while((ch=getchar())!='\n')
  {
    if( scanf("%d %d",&rows,&cols)!=2)
    break;
     display(ch,rows,cols);
     while(getchar()!='\n')      /*剔除掉scanf()输入后的所有字符.*/
     {

        printf("1");          /*后面有多少字符就输出多少个1*/
        continue;

     }
     printf("Enter another character and tow integers;\n");
     printf("Enter a newline to quit.\n");
  }
  printf("Bye.\n");
  return 0;
}
void display(char cr,int lines,int width)
{
  int row ,col;
  for(row =1;row<=lines;row++)
  {
    for(col=1;col<=width;col++)
    {
      putchar(cr);
       }
      putchar('\n');

  }
}

输出结果:
Enter a character and tow integers:
d 3 4
dddd
dddd
dddd
Enter another character and tow integers;
Enter a newline to quit.
d 3 4
dddd
dddd
dddd
11Enter another character and tow integers;
Enter a newline to quit.

 

 

 

 

posted on 2006-11-03 14:12 matthew 阅读(2534) 评论(1)  编辑  收藏 所属分类: 数据结构与算法设计

FeedBack:
# re: C语言的混合输入数字和字符问题 2010-11-23 13:40 冰尘
我觉得只要在调用函数后面加上 getchar(); 也可以解决。。  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: