一个疑惑??????
#include <stdio.h>
struct stu_type
{
char name[30];
int num;
int score[3];
};
main()
{
struct stu_type stu1;
printf( "please input name num score1 score2 score3\n ");
printf( "name num score1 score2 score3:\n ");
scanf( "%s %d %d %d %d\n ",stu1.name,&stu1.num,&stu1.score[0],&stu1.score[1],&stu1.score[2]);
print(stu1);
getch();
}
print(struct stu_type stu)
{
printf( "%s %d %d %d %d\n ",stu.name,stu.num,stu.score[0],stu.score[1],stu.score[2]);
}
在运行后
输入FF 12 34 45 56 回车 没反应
再随便输入些如KJK 回车,才能打印出我输入的
怎样一个回车就可以打印出我输入的
[解决办法]
scanf这里 " "中去掉\n。
scanf()函数中,转义字符如(\n),系统并不把它们当成转义字符来解释,而是将其视为普通字符,要求原样输入。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j,k;
int n;
n=scanf( "%d%d%d ",&i,&j,&k);
printf( "n=%d i=%d j=%d k=%d\n ",n,i,j,k);
system( "pause ");
return 0;
}
输入1 2 3
输出n=3 i=1 j=2 k=3
输入1.0 2 3
输出n=1 i=1 j=24 k=0
输入1 2.0 3
输出n=2 i=1 j=2 k=0
输入1 2 3.0
输出n=3 i=1 j=2 k=3
看出点名堂来了吧,scanf函数从左至右依次读取数据存入相应位置,当遇到“非法数据”,对其进行强制转换读取(这里为截断),由于此时缓冲区中残留该“非法数据”部分信息,再读取时失败,程序返回读取失败前所有成功读取的个数(包括强制转换的“非法数据”)。至于遗留在缓冲区的内容,则按某种规律顺序赋给剩余地址处!(似乎不是随机的)
这个在baidu里一搜一堆 - -