首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

输入函数scanf()解释,该怎么解决

2013-03-21 
输入函数scanf()解释#include stdio.hint main(void){int m,nchar a,bm scanf(%c,&a)n scanf(

输入函数scanf()解释

#include <stdio.h>
int main(void)
{
    int m,n;
char a,b;
m = scanf("%c",&a);
n = scanf("%c",&b); //----------(*)
printf("%d %d %c %c\n",m,n,a,b);
    return 0;
}


输入:a回车
输出了:1 1 a回车
当(*)句改为n = scanf(" %c",&b); 输入输出和想的就一样了
为什么,那个空格起了什么作用
[解决办法]
当执行完第一个scanf时,输入流里还有一个回车符没匹配
如果没有空格,%c会将回车符匹配上,相当于输入了两个字符
加一个空格,第二句就需要有两个字符才能匹配
只有一个回车符就不能被匹配成功,只能等下一个输入字符,正好和%c匹配
这样执行完,还剩余一个回车符在输入流里
[解决办法]
int scanf ( const char * format, ... );

format  C string that contains a sequence of characters that control how characters extracted from the stream are treated:
1. Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).
2. Non-whitespace character, except format specifier (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.
3. Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored into the locations pointed by the additional arguments.

[解决办法]
#include <stdio.h>
char s[]="123 ab 4";
char *p;
int v,n,k;
void main() {
    p=s;
    while (1) {
        k=sscanf(p,"%d%n",&v,&n);
        printf("k,v,n=%d,%d,%d\n",k,v,n);
        if (1==k) {
            p+=n;
        } else if (0==k) {


            printf("skip char[%c]\n",p[0]);
            p++;
        } else {//EOF==k
            break;
        }
    }
    printf("End.\n");
}
//k,v,n=1,123,3
//k,v,n=0,123,3
//skip char[ ]
//k,v,n=0,123,3
//skip char[a]
//k,v,n=0,123,3
//skip char[b]
//k,v,n=1,4,2
//k,v,n=-1,4,2
//End.

热点排行