C:将字符串数组转换为浮点数组,或者将带有浮点的文件读取为浮点而非字符串



我不想读取一个文件(每一行中有10K个浮点数(,并找到它的max_val元素(我现在还不远(。我设法将文件放入一个char数组,但我需要它是一个float数组才能找到最大值。

谢谢你的帮助。

#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]){
char nameDatei[100];

if(argv[1] != NULL) {
strcpy(nameDatei, argv[1]);
} else {
printf("type in the name of the file: ");
scanf("%s", nameDatei);
}

//read file;
FILE *fPointer;
fPointer = fopen("findMaxOfFloats.txt", "r");
//save
char singleLine[100];
char content[10000][100];
int i = 0;

while (!feof(fPointer)){
if (fgets(content[i], sizeof(singleLine), fPointer) != NULL)
i++;    
}
fclose(fPointer);

//print the array
for(int loop = 0; loop < 10000; loop++){
printf("%s", content[loop]);
}

//find max...
return 0;
}

一些问题。。。

  1. 您将一行读取到singleLine中,但不将其复制到content
  2. feof坏——只需检查fgets的返回值
  3. 您希望contentdouble,而不仅仅是char数组
  4. 执行fgets之后,您可以/应该使用strtodsingleLine中的字符串转换为二进制/浮点值
  5. 您希望保留读取的行数计数(即content中的有效元素数(
  6. 您从argv[1]scanf中获取文件名,但随后使用硬连接的名称
  7. 您没有检查fopen的返回值

这是重构后的代码。注释:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXCONTENT      10000
int
main(int argc, char *argv[])
{
char nameDatei[100];
if (argv[1] != NULL) {
strcpy(nameDatei, argv[1]);
}
else {
printf("type in the name of the file: ");
scanf("%s", nameDatei);
}
// read file;
FILE *fPointer;
// NOTE/BUG: You get a filename from either argv[1] or scanf but don't use it
#if 0
fPointer = fopen("findMaxOfFloats.txt", "r");
#else
fPointer = fopen(nameDatei, "r");
if (fPointer == NULL) {
perror(nameDatei);
exit(1);
}
#endif
// save
char singleLine[100];
#if 0
char content[10000][100];
#else
double content[MAXCONTENT];
#endif
#if 0
int i = 0;
while (!feof(fPointer)) {
if (fgets(content[i], sizeof(singleLine), fPointer) != NULL)
i++;
}
#else
int count = 0;
// read in all lines until EOF
while (fgets(singleLine,sizeof(singleLine),fPointer) != NULL) {
// don't overflow the array
if (count >= MAXCONTENT) {
printf("count too largen");
exit(1);
}
// decode the number
char *cp;
content[count] = strtod(singleLine,&cp);
// check for syntax error
if (*cp != 'n') {
printf("syntax error: %s",singleLine);
exit(1);
}
++count;
}
#endif
fclose(fPointer);
// print the array
for (int idx = 0;  idx < count;  ++idx)
printf("%gn", content[idx]);
// find max... [and min, too ;-)]
double max = content[0];
double min = content[0];
for (int idx = 0;  idx < count;  ++idx) {
// get the current value
double cur = content[idx];
// set new maximum
if (cur > max)
max = cur;
// set new minimum
if (cur < min)
min = cur;
}
printf("min=%g max=%gn",min,max);
return 0;
}

在上面的代码中,我使用了cpp条件词来表示旧代码与新代码:

#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif

注意:这可以通过unifdef -k运行文件来清除

最新更新