c - 如何在C中读取每行带有数字的文件?
问题描述
我正在尝试读取一个包含 10 个数字的文件,然后将它们添加到一个数组中,以便稍后对它们进行排序,但我无法读取它们。不知道为什么这对我不起作用,有人可以解释一下吗是错的?每行只有一个数字。
10.05
11.01
9.03
double nums[10] = {0};
int count;
if ((fptr = fopen("filename", "r")) == NULL){
printf("Error opening file.\n");
}
while ((c = getc(fptr)) != EOF){
if (c != '\n'){
nums[count] = (double)c;
count = count + 1;
}
}
fclose(fptr);
解决方案
怎么了:
- 您只存储一个字符。
- 您
count
每次都在非换行符上更新,而更新应该在换行符上。 count
未经初始化就使用。- 转换
double
为不适合这种用法。
可能的修复:
int c;
FILE* fptr;
char line[1024]; // add line buffer and size tracking
int lineCount = 0;
double nums[10] = {0};
int count = 0; // initialize count
if ((fptr = fopen("filename", "r")) == NULL){
printf("Error opening file.\n");
} else { // avoid using NULL to read file
while ((c = getc(fptr)) != EOF){
if (c == '\n'){ // update nums on newline character
line[lineCount] = '\0'; // don't forget to terminate the string
nums[count] = atof(line); // atof() from stdlib.h is useful to convert string to number
count = count + 1;
lineCount = 0; // start to read next line
} else { // read line contents
line[lineCount] = (char)c;
lineCount = lineCount + 1;
}
}
fclose(fptr);
}
推荐阅读
- image - 如何将图像上传到不同的文件夹?
- android - okHttp3保持活动连接不起作用
- python-3.x - Pandas 将多列分组为一列
- sqlite - 将数据库从 SQLite 更改为 SQLCipher 后升级应用程序时遇到问题
- gatling - 我们如何同时执行两个 post 请求
- c++ - 是否可以从父类“this”指针类型转换到子类
- ios - Swift 中的 UITextStorageDirection 和 UITextLayoutDirection 枚举是什么?
- java - 将 SQL 语句写入文件
- java - 如何在所有窗口顶部打开 FileDialog
- wordpress - 如何始终在 wordpress 管理中的页面列表中显示行操作