【发布时间】:2020-12-22 03:28:21
【问题描述】:
我正在从文件“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
如何避免?
【问题讨论】:
-
while ((i + 1 < MAXCN) && ((lstm = fgetc(fp)) != ' ') && lstm != '\n' && (lstm != EOF))??只需添加支票lstm != '\n'。 -
注意,在实际代码中还应避免使用
atof()或atoi()等。提供对转换的零错误检查,并且很乐意接受atof ("my cow");返回0而没有任何错误指示。而是使用strtof()(或至少sscanf()——这也将消除您检查lstm != '\n'的需要)