C语言从文本文件中读取数据时忽略回车(换行)

ingore Enter(line break) when read data from text file in C language

我正在从文件“test1.txt”中读取一些数据,一切正常,但是当遇到 Enter(换行符)时,它给出了我不想要的答案

代码和文件:

main.c:

#include "fscan.h"
#include <stdio.h>
 
int main(){
    float lstm_val;
    int row;
    int col;
    float dense[2][4];
    FILE *fp = fopen("test1.txt","r");
    for (row = 0; row < 2; row++){
        for (col = 0; col < 4; col++){
            lstm_val = fscan(fp);
            dense[row][col] = lstm_val;
        }
    }

    return 0;
}

fscan.c:

#include <stdlib.h>
#include <stdio.h>
#define MAXCN 50

float fscan(FILE *fp)
{   //FILE* lstm_txt = NULL;
    char lstm_weight[MAXCN] = {0};
    int lstm = 0;
    int i = 0;
    float lstm_val;
    
    while ((i + 1 < MAXCN) && ((lstm = fgetc(fp)) != ' ')  && (lstm != EOF)){
        lstm_weight[i++] = lstm;
    }
    printf("\n lstm_weight: %s\n\n", lstm_weight);
    lstm_val = atof(lstm_weight);
    printf("\n convert \"lstm_weight\" to lstm_val is : %f\n\n", lstm_val);
    return lstm_val;
 }

fscan.h:

#include <stdio.h>

extern float fscan(FILE *fp);

test1.txt:

4.217959344387054443e-01 -2.566376626491546631e-01 2.173236161470413208e-01 4.217959344387054443e-01
2.173236161470413208e-01 4.217959344387054443e-01 4.217959344387054443e-01 -2.566376626491546631e-01 

enter image description here 第一行最后一个“4.217959344387054443e-01”和第二行第一个“2.173236161470413208e-01”之间是一个回车,显然,遇到这个回车结果是错误的

结果是:

 lstm_weight: 4.217959344387054443e-01


 convert "lstm_weight" to lstm_val is : 0.421796


 lstm_weight: -2.566376626491546631e-01


 convert "lstm_weight" to lstm_val is : -0.256638


 lstm_weight: 2.173236161470413208e-01


 convert "lstm_weight" to lstm_val is : 0.217324


 lstm_weight: 4.217959344387054443e-01
2.173236161470413208e-01


 convert "lstm_weight" to lstm_val is : 0.421796


 lstm_weight:


 convert "lstm_weight" to lstm_val is : 0.000000


 lstm_weight: 4.217959344387054443e-01


 convert "lstm_weight" to lstm_val is : 0.421796


 lstm_weight: 4.217959344387054443e-01


 convert "lstm_weight" to lstm_val is : 0.421796


 lstm_weight: -2.566376626491546631e-01


 convert "lstm_weight" to lstm_val is : -0.256638

如何避免?

我正要写出解决方案,但感谢 Rankin 先生,他解释得很好。它与转义序列有关。例如 Enter 实际上是 \n,其中所有计算机需要理解并以换行符 (\n) 或制表符 (\t) 显示它的地方。 检查此以获取更多信息:Wikipedia - Table of Escapes

如果有什么需要省略的,比如 ,你必须实现它 lstm != ',' 。 这有时用于可读性 42,376.98(四万二千三百七十六点九八)例如

最终代码将是

while ((i + 1 < MAXCN) && ((lstm = fgetc(fp)) != ' ') && (lstm != '\n') && (lstm != EOF))

查看 David C. Rankin 的答案以及维基百科 link 的转义序列。 更多关于:

此外,Linux man pages online (man7.org) 可以为您可能遇到的任何标准函数提供正确的用法。