从fgets char数组中删除空格

时间:2019-01-20 19:20:03

标签: c

我正在尝试制作一个程序,计算给定字符串中整数的平均值,然后将其相加,直到遇到-1,样本输入为1 2 3 4 5 -1

如何从数组中删除空格,以便求和计算?

#include <stdio.h>
#include <stdlib.h>
#include "source.h"
#include <string.h>
#include <ctype.h>

#define MAX_LEN 1000

void calculate_average() {
    int test, size, sum, i, j, k, temp;
    int grade;
    char input[MAX_LEN];
    char formattedInput[MAX_LEN];
    double avg;
    size = 0;
    avg = 0.0;
    test = 1;
    k = 0;
    sum = 0;

    fgets(input, 10, stdin);
    for (j = 0; j < strlen(input); ++j) {
        if (input[j] = ' ') {
            ;
        } else {
            temp = input[j];
            formattedInput[k] = temp;
            ++k;
        }
    }

    for (i = 0; atoi(input[i]) != -1; ++i) {
        if (atoi(formattedInput[i]) == -1) {
            test = -1;
            avg = sum / size;
        } else {
            ++size;
            sum = sum + atoi(formattedInput[i]);
        }
    }

    printf("%f\n", avg);
}

2 个答案:

答案 0 :(得分:2)

我建议您使用strtod,以便无需预处理即可处理输入字符串,
附带说明一下,原始代码sum / size将强制转换为int,并且您将失去精度,因此需要先强制转换
我将您的功能更改如下

#define MAX_LEN 1000

void calculate_average(){
    int sum = 0;
    int count = 0;
    char input[MAX_LEN];

    fgets(input, 10, stdin);

    char *start, *end;
    start = input;
    while(1){
        int temp = strtod(start, &end);
        if(temp == -1)
           break;
        if(*end == 0)
            break;
        start = end;
        sum += temp;
        count++;
    }

    double avg = (double)sum / count;
    printf("%f\n", avg);
}

答案 1 :(得分:1)

您可以将sscanf%n格式说明符一起使用以空格分隔的数字来读取。

示例:

int temp = 0;
int bytesread = 0;
char *ptr = input;
while (sscanf(ptr, "%d%n", &temp, &bytesread) > 0 && temp != -1) {
   ptr += bytesread;
   sum = sum + temp;
}

%n将返回从字符串读取的字节数,因此使用此值将ptr移至指向下一个数字。

相关问题