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

Scanf won't notice '\n' char in a program loading only numbers

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

问题是,对于如何解决输入问题,我想不出任何想法:他要求我们在用户不输入任何内容时结束程序,所以我接受了输入 - \n 符号。 我可以使用 fgets 获取第一个变量但是: 首先,我觉得除了数组之外,我不知道还有什么其他方法可以让用户输入一个长十进制数(以 char 数组的形式,其中包含构成数字的元素)。我不知道他的脚本是否没有在其中放置一些 "rofl" 数字。 其次,在这种情况下,我认为从一个 X 中剥离该数组将完全破坏该程序的整体结构。我宁愿同时接受 X 和 Y 并将它们接受为 char 类型,但是像 atof 这样的函数可能只理解 X 并且会在 \n 符号后停止工作。 所以 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;
}

你的问题,用fgets读一整行,可能用sscanf解析出这两个数字可能有效。

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

使用 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 是一个 "scanset" ,它告诉 scanf 读取除 '\n' 之外的所有内容,一旦到达换行符,它就会读取换行符并忽略它。

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

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