scanf如何在前一行之前工作?

时间:2013-09-18 08:46:37

标签: c

在下面的代码中,当我在[a-z]中输入任何内容,然后在c中输入\ n时,它接受并输出'enter d'。但是,当我为c提供任何数字时,会扫描该值以查找变量d,然后仅显示“输入d”。这是怎么发生的?

#include<stdio.h>

void main()
{
    char c[10],d[10];
    int i,j;

    printf("enter c:");
    i=scanf("%[a-z]%1[\n]",c);

    printf("\nenter d:");
    j=scanf("%[ 0-9]%1[\n]",d);

    printf("\nc : %s-%d\n",c,i);
    printf("\nd : %s-%d\n",d,j);
 }

我的输出是:

enter c:12

enter d:c:�-0

d:12-2

2 个答案:

答案 0 :(得分:2)

如果你想跳过空格,比如结尾换行符,那么在格式代码之前添加一个前导空格:

printf("enter c: ");
i = scanf(" %s", c);

printf("enter c: ");
j = scanf(" %s", d);

这将使scanf跳过所有空格。

另外,如果你想读一个数字,为​​什么不用数字作为数字读取它? "%d"格式代码?如果你想要它作为一个字符串,那么使用例如snprintf在扫描后进行转换。

答案 1 :(得分:1)

试试这个:

#include<stdio.h>
#include <stdlib.h>

int main()
{
    char *c = malloc(10);
    char *d = malloc(10);

    int i = 0;

    printf("enter c:");
    int x = EOF;
    while (( x = getchar()) != '\n' && x != EOF) {
        if (i >= 10) {
            break;
        }
        if (x >= 97 && x <= 122) {
            c[i++]=(char)x;
        }
    }
    printf("\nenter d:");
    x = EOF;
    i = 0;
    while (( x = getchar()) != '\n' && x != EOF) {
        if (i >= 10) {
            break;
        }
        if (x >= 48 && x <= 57) {
            d[i++]=(char)x;
        }
    }
    printf("\nc : %s\n",c);
    printf("\nd : %s\n",d);
    return 1;
 }