C 我想从包含整数和浮点数的文件中读取数据

C 我想从包含整数和浮点数的文件中读取数据,c,C,我想从包含整数和浮点数的文件(使用C)中读入数据,但我只想将浮点数放入数组中。我不知道如何避免整数。 这是数据集的一个示例: 2019 001 3.55 4.63 3.14 4.56 4.21 2.33 2019 002 4.58 5.94 6.16 7.28 8.61 9.91 一个有趣的解决方案是将所有输入读取为float,将它们转换为int,并比较这两个变量是否相等。如果不相等,一些舍入意味着它是一个浮点,否则它是一

我想从包含整数和浮点数的文件(使用C)中读入数据,但我只想将浮点数放入数组中。我不知道如何避免整数。 这是数据集的一个示例:

2019 001    3.55    4.63    3.14    4.56    4.21    2.33
2019 002    4.58    5.94    6.16    7.28    8.61    9.91

一个有趣的解决方案是将所有输入读取为float,将它们转换为int,并比较这两个变量是否相等。如果不相等,一些舍入意味着它是一个浮点,否则它是一个整数

请记住,浮点变量不是精确的表示,因此您可能希望为比较添加适合您的用例的适当阈值

#include <stdio.h>

int main(void) {
  FILE *myFile;
    myFile = fopen("test.txt", "r");
    float numberArray[16];
    int i;

    for (i = 0; i < 16; i++)
    {
        fscanf(myFile, "%f", &numberArray[i]);
    }

    for (i = 0; i < 16; i++)
    {
      int temp = (int)numberArray[i];
      if( numberArray[i] != temp ){
        printf("Float: %f\n\n", numberArray[i]);
      }
      else{
        printf("Int: %d\n\n", temp);
      }
    }
}
#包括
内部主(空){
文件*myFile;
myFile=fopen(“test.txt”、“r”);
浮点数雷[16];
int i;
对于(i=0;i<16;i++)
{
fscanf(myFile、%f、&numberraray[i]);
}
对于(i=0;i<16;i++)
{
int temp=(int)numberArray[i];
if(numberArray[i]!=temp){
printf(“浮点:%f\n\n”,numberArray[i]);
}
否则{
printf(“Int:%d\n\n”,temp);
}
}
}

我希望您的问题能够区分int和float,因为数字是否应该包含小数点。否则,所有整数也可以是浮点数。因此,我假设123不是浮动,123.000也不是浮动

话虽如此,一个聪明的解决方案是把所有的数字读作浮点数。从文件读取数据时,将数字指定给int变量。如果整数不能包含该数字,则可以将该数字添加到数组中

比如说,

float input = 123.45;
int n = input; // n is 123
// If input cannot be shaped to an int
if (n != input)
    addToArray(input);
现在,这只是实现这一逻辑的问题:

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

// Change this according to your requirements
#define INPUT_FILE "data_set.txt"
#define ARRAY_SIZE 100

int main()
{
    float arr[ARRAY_SIZE];
    float data;
    int n;
    int i = 0;
    FILE* input_file = fopen("data_set.txt", "r");

    if (!input_file)
    {
        printf("ERROR: Could not open the file!");
        exit(EXIT_FAILURE);
    }

    while (fscanf(input_file, "%f", &data) != EOF)
    {
        // Truncate the number to an integer
        n = data;

        // Take the number if it cannot be an integer
        if (n != data)
        {
            arr[i] = data;
            ++i;
        }
    }

    // Display the output and check the result
    n = i;
    for (i = 0; i < n; ++i)
        printf(" %g", arr[i]);

    fclose(input_file);
    return 0;
}
#包括
#包括
//根据您的要求进行更改
#定义输入文件“data\u set.txt”
#定义数组大小为100
int main()
{
浮动arr[数组大小];
浮动数据;
int n;
int i=0;
FILE*input_FILE=fopen(“data_set.txt”、“r”);
如果(!输入_文件)
{
printf(“错误:无法打开文件!”);
退出(退出失败);
}
while(fscanf(输入文件、%f、&data)!=EOF)
{
//将数字截断为整数
n=数据;
//如果数字不能是整数,则取该数字
如果(n!=数据)
{
arr[i]=数据;
++一,;
}
}
//显示输出并检查结果
n=i;
对于(i=0;i

如果数据集中的元素数未知,请使用动态数组。

看起来它遵循固定格式,那么为什么不读取整数并丢弃它们呢?这些不是整数和浮点数。是文字!(这是一个关键区别.)格式规范
%*d
可用于跳过不需要的整数。不应提供任何目标。具体取决于。你想要多严格?这会一直是输入格式吗?2019年不也是一个浮动吗?谢谢^^如果你的答案被接受,我不会感到惊讶,因为它更好written@pastaleg当我看到代码中使用的数学函数时,我认为您实现了不同的逻辑。我的错,我已经把你的答案高估了:)