Scanf没有注意到' \ n'在一个只加载数字的程序中的char

时间:2018-03-19 20:44:38

标签: c input scanf whitespace

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

问题在于,我无法提出任何有关如何通过输入来解决问题的想法:他要求我们在用户没有输入任何内容后让程序结束,所以我采取了它用于输入 - \ 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;
}

2 个答案:

答案 0 :(得分:0)

至于你的问题,使用fgets读取整行,并且可能使用sscanf来解析这两个数字可能有效。

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

答案 1 :(得分:0)

如何使用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 '-'