#include
#include
int main()
{
int a[100][100],b[100][100],c[100][100];
int f,i,j,k,m,n;
int s=0,t=0,r=0,l=0;
char ch;
ch=getchar();
while(ch!='.')
{
if(ch!=' ')
s++;
if(ch!='\n'&&ch!=' ')
t++;
r++;
ch=getchar();
}
while(getchar()!='\n');
m=s-t+1;
n=(r-t)/m+1;
for(i=0;ifor(j=0;j"%d",&a[i][j]);
}
}
for(i=0;ifor(j=0;j"%d",&b[i][j]);
}
}
for(i=0;ifor(j=0;jfor(k=0;k*b[k][j];
c[i][j]=l;
printf("%d ",c[i][j]);
l=0;
}
printf("\n");
}
}
就是getchar()之后缓冲区被清洗,scanf()要求的值要重新输入一遍,有没有解决办法?
不知道你这个问题是否已经解决, 如果还没有解决的话:假设程序要求用getchar()处理字符输入,用scanf()处理数值输入,这两个函数都能很好的完成任务,但是不能混合使用。 因为getchar()读取每个字符,包括空格、制表符和换行符;而scanf()在读取数字时则会跳过空格、制表符和换行符。
例:
要求用户输入一个字母和两个数字,输出以第一个数字为行数,第二个数字为列数,以字母为内容的数列,要求可以不断输入直至键入回车退出程序:
#include <stdio.h>
void display(char cr,int lines,int width);
int main(int argc, const char * argv[]) {
int ch;
int rows,cols;
printf("Enter a character and two integers:\n");
while((ch=getchar())!= '\n'){
scanf("%d %d", &rows,&cols);
display(ch, rows, cols);
printf("Enter another character and two 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');
}
}
output:
我们发现,在第一次输入成功打印后,程序自动退出。这明显不符合我们的题目要求。
原因是,输入的c23其实是c23+换行符
,scanf()函数把这个换行符留在了缓存中。getchar()不会跳过换行符,所以在进入下一轮迭代时,还没来得及输入字符,它就读取了换行符,然后将其赋值给了ch。而ch是换行符正式终止循环的条件。
如何改进??
#include <stdio.h>
void display(char cr,int lines,int width);
int main(int argc, const char * argv[]) {
int ch;
int rows,cols;
printf("Enter a character and two integers:\n");
while((ch=getchar())!= '\n'){
if( scanf("%d %d", &rows,&cols)!=2 ){
break;
}
display(ch, rows, cols);
while(getchar()!='\n'){
continue;
}
printf("Enter another character and two 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');
}
}
Output:
题外话:
scanf()中转化符的问题
问题:从上面两张图片中可以看出,当scanf("%d",&c);
改为scanf("%c",&c);
时,控制台中出现了图二的问题。character为什么为空白??
原因:
如果格式是%c,那么任何字符都是它想要的,所以第二个程序中的第二个scanf("%c")会得到‘+’后面的空格’ '。如果格式是%d,则会忽略任何空白字符(空格、回车、制表符等),忽略的意思是,从缓冲区里删除,但并不保存;如果遇到数字,则拿出并保存给后面的整数,也就是说%d的时候,scanf想要的字符是数字和空白符。所以第一个程序里的第二个scanf("%d")忽略掉了空格,正确输入了数字。
你的输入格式是什么?
while(ch!='.')
{
if(ch!=' ')
s++;
if(ch!='\n'&&ch!=' ')
t++;
r++;
ch=getchar();
}
while(getchar()!='\n');
这些代码用意不明