为什么scanf继续扫描以寻找其他用户输入?

时间:2019-04-08 02:40:56

标签: c scanf

我正在实现Graph并尝试获取用户输入以输入“顶点和边”。我正在使用scanf()来读取用户输入,看起来scanf的行为异常。

我需要两个顶点号才能在它们之间占据优势,并且我正在使用2个scanf调用(尝试使用单个scanf来读取两个输入)以在每次循环旋转时读取用户输入用户在开始时输入的边数。

而且,由于scanf的问题,我不得不移出scanf到main()来读取边数和顶点数。

问题是,在scanf("%d\n", &u);,我(用户)输入的数字后面是“ Enter”,它等待其他输入。当我输入另一个数字并按下Enter键后,它将移至下一段代码。

我不确定scanf为何会这样。

为更好地理解,请查看代码及其输出。

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

typedef struct Graph
{
    int V;
    int E;
    int **arr;
} GRAPH_t, *GRAPH_p;

GRAPH_p adj_matrix(int e, int v)
{
    GRAPH_p g = malloc(sizeof(GRAPH_t));

    if(g == NULL)
    {
        printf("ERROR: malloc dint work");
        return NULL;
    }

    g->E = e;
    g->V = v;

    g->arr = (int**)malloc(sizeof(int *) * v);
    for(int i = 0; i < g->V; i++)
    {
        g->arr[i] = (int *)malloc(sizeof(int)*v);
    }

    for(int u = 0; u < g->E; u++)
    {
        for(int v = 0; v < g->V; v++)
        {
            g->arr[u][v] = 0;
            printf("%d ", g->arr[u][v]);
        }
        printf("\r\n");
    }

    return g;
}

int main()
{
    int vertx = 0;
    int edge = 0;
    printf("Enter Vetrexes \r\n");
    scanf("%d", &vertx);
    printf("Enter Edges \r\n");
    scanf("%d", &edge);

    GRAPH_p g = adj_matrix(edge,vertx);

    int u = 0;
    int v = 0;
    for(int i = 0; i < g->V; i++)
    {
        printf("Please enter v0\n");
        scanf(" %d\n", &u );
        printf("Please enter v1\n");
        scanf(" %d\n", &v );
        printf("You entered %d and %d", u,v);
        g->arr[u][v] = 1;
    }

    for(int u = 0; u < g->E; u++)
    {
        for(int v = 0; v < g->V; v++)
        {
            printf("%d ", g->arr[u][v]);
        }
        printf("\r\n");
    }

    free(g);
    //printf("You Entered %d\r\n", i);
    return 0;
}

输出:

Enter Vetrexes 
3
Enter Edges 
3
0 0 0 
0 0 0 
0 0 0 
Please enter v0
0
1        <----------------This is the problem
Please enter v1
2
You entered 0 and 1
Please enter v0
1
Please enter v1
2
You entered 2 and 1
Please enter v0
0
Please enter v1
1
You entered 2 and 0
0 1 0 
0 0 0 
1 1 0 
Program ended with exit code: 0

0 个答案:

没有答案