c - C 编码 - 文本文件中的第一个数字没有按我预期的方式读取
问题描述
我正在执行一个功能,该功能包括读取我编写的文件的元素并打印它们。问题是,似乎文本文件每一行的第一个数字正在以一种我不明白它是如何到达的方式被读取和打印。它主要是 90-110 和零的数字。
我尝试将变量更改为字符和浮点数,但都没有奏效。
void imprimir_tabela(){
FILE *tabela = fopen("tabela.txt", "r");
if(tabela == NULL){
printf("TABELA INVALIDA OU NAO ACHADA");
printf("erro 404");
exit(404);
}
int numero_atomico;
char abreviacao;
char nome[20];
float massa_atomica;
int grupo;
int periodo;
while(!feof(tabela))
{
fscanf(tabela, "%d %s %s %f %d %d", &numero_atomico, &abreviacao, &nome, &massa_atomica, &grupo, &periodo);
printf("%d - %s - %s - Massa atomica: %0.3f - Grupo: %d - Periodo: %d\n", numero_atomico, &abreviacao, &nome, massa_atomica, grupo, periodo);
}
rewind(tabela);
return 0;
文本文件的示例行
1 H Hidrogenio 1.008 1 1
2 He Helio 4.003 18 1
3 Li Litio 6.941 1 2
解决方案
请参阅下面代码中的注释
void imprimir_tabela(){
FILE *tabela = fopen("tabela.txt", "r");
if(tabela == NULL){
printf("TABELA INVALIDA OU NAO ACHADA");
printf("erro 404");
exit(404);
}
int numero_atomico;
char abreviacao;
char nome[20];
float massa_atomica;
int grupo;
int periodo;
do { // Use to be while(!feof(tabela)) - See link in the comments section
{
// 1 H Hidrogenio 1.008 1 1
// For reference
// 1. Prevent buffer over run
// 3. record return value
int ret = fscanf(tabela, "%d %c %19s %f %d %d\n", &numero_atomico, &abreviacao, &nome, &massa_atomica, &grupo, &periodo);
switch (ret) {
case 6: // Ok
printf("%d - %c - %s - Massa atomica: %0.3f - Grupo: %d - Periodo: %d\n", numero_atomico, abreviacao, &nome, massa_atomica, grupo, periodo);
break;
case EOF: // End of file - we are done
break:
default:
// Report error - take some action - in this case exit
fprintf(stderr, "Error in file %s\n", "tabela.txt");
exit(-1);
// Are we done
} while (ret != EOF);
// rewind(tabela); - Not required
// But this is
fclose(tabela);
return 0;
}
请修正缩进 - 我把它作为练习留给读者
推荐阅读
- php - laravel 可以像 mysql password() 函数那样做密码加密吗?
- stm32 - STM32F103 RTOS 线程之间的延迟
- android - 错误:com.google.android.exoplayer2 包不存在
- python - 如何在熊猫现有索引之间添加数据框的索引?
- elasticsearch - Logstash 根据字段值添加动态白名单名称
- linux - 比较两个文件并在文件名匹配时打印行 - 大文件
- javascript - 使用 chokidar 将新文件从一个位置移动到另一个位置以在 nodejs 和 powershell 脚本中进行监控
- c++ - 在 C++ 中包含用于项目的 OpenCV
- php - PHP 致命错误:未捕获的 PDOException:SQLSTATE [IMSSP]:查询的活动结果不包含任何字段
- php - 检查您正在使用的 MariaDB 版本的文档,以了解第 1 行的“DESC LIMIT 1) LIMIT 0, 50”周围的正确语法