代码之家  ›  专栏  ›  技术社区  ›  user9511542

Scanf不会注意到仅加载数字的程序中的“\n”字符

  •  0
  • user9511542  · 技术社区  · 7 年前

    我已经搜索了几天,我只找到了一个在我看来并不完美的解决方案。我们的老师让我们创建一个函数来计算用户提供的点之间的总距离。 我的想法是这样编写代码,使用特定类型的数组。

    问题是,我想不出任何方法来解决输入问题:他要求我们在用户未键入任何内容时结束程序,因此我将其视为输入符号。 我可以使用fgets获取第一个变量,但: 首先,我觉得除了数组之外,我不知道还有什么其他方法可以保存一个长的十进制数(以字符数组的形式,其中的元素构成数字),用户可以将其放入输入中。我不知道他的剧本里是否有“rofl”的数字。 第二,在这种情况下,我认为从一个X上去掉这个数组将完全破坏这个程序的整体结构。我宁愿将X和Y都作为char类型接受,但是像atof这样的函数可能只理解X,并且在符号之后停止工作。 所以Y将不被给出。接受的输入编号应为双精度类型。例如:

    2 2
    3 3
    -2 4.5
    

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #include<math.h>
    double lenght(struct point *coordinates, int n);
    struct point {
       double   x;
       double   y;
    };
    
    int main()
    {
        double x,y,TwiceAsBig=3;
        int i=0,l=0;
        struct point *coordinates;
        coordinates = (struct point*)malloc(sizeof(*coordinates)*3);
        //allocation of memory for pointtype array with a pointer
        while(scanf("%lg %lg",&x,&y)==2)
        {
             coordinates[i].x=x;
             coordinates[i].y=y;
             i++;
             if(i==TwiceAsBig)
             {
                coordinates = (struct point*)realloc(coordinates, 2*i*sizeof(*coordinates));
                TwiceAsBig=2*TwiceAsBig;
             }
        }
        printf("\n");
        for(l;l<i;l++)
        {
             printf("%lg %lg\n", coordinates[l].x,coordinates[l].y);
        }
        //checking on the array if the values were loaded correctly
        printf("%lg",lenght(coordinates,i));
    }
    
    //function for dinstace in between the points
    double lenght(struct point*coordinates,int n)
    {
        int l=0;
        for(l;l<n;l++)
        {
            printf("%lg %lg\n", coordinates[l].x,coordinates[l].y);
        }
    
        int pair=0;
        double lenght,distance;
        for(int AoP;AoP<n-1;AoP++)
        {
            distance=sqrt(pow(coordinates[pair+1].x-coordinates[pair].x,2)+pow(coordinates[pair+1].y-coordinates[pair].y,2));
            pair++;
            printf("%lg: ", distance);
            lenght=lenght+distance;
        }
        return lenght;
    }
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   Some programmer dude    7 年前

    对于您的问题,使用 fgets 阅读整行文字,以及可能的用法 sscanf 解析出这两个数字可能有用。

    仅使用的问题 scanf 所有数字格式说明符都会自动读取并跳过前导空格,换行符是一个空格字符。这意味着你 scanf公司 循环中的调用条件将等待,直到输入了一些实际的非空格字符(后面当然是换行符,这将导致循环重新开始)。

        2
  •  0
  •   Witnessthis    7 年前

    那么使用 scanf("%[^\n]%*c", test); 读取完整字符串。

    然后使用sscanf分析结果?

    类似这样:

    char* userinput = (char*) malloc(sizeof(char) * 100);
    scanf("%[^\n]%*c", userinput);
    
    double a, b;
    sscanf(userinput, "%lg %lg", &a, &b);
    printf("sum %lg\n", a+b);
    

    有输入 "-5.5 3.2" 代码生成 "sum -2.3"

    %[^\n]%*c 是一个“扫描集”,它告诉scanf读取除“\n”以外的所有内容,一旦到达换行符,它将读取换行符并忽略它。

    您甚至可以使用扫描集,通过指定希望读取的字符类型,在某种程度上检查输入。

    %[0-9 .\\-] // would read digits from 0-9, 'space', '.' and '-'