簡體   English   中英

C 編碼 - 文本文件中的第一個數字未按我預期的方式讀取

[英]C coding - First number in text file not being read the way I expected

我正在做一個 function ,其中包括讀取我編寫的文件的元素並打印它們。 問題是,似乎文本文件每一行的第一個數字正在以一種我不明白它是如何到達的方式被讀取和打印。 它主要是 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;
}

請修正縮進 - 我把它作為練習留給讀者

至少這個問題:讀入char就好像它對於string來說已經足夠了。

char abreviacao;

//                    vv --- needs more meory than 1 `char`
fscanf(tabela, "%d %s %s %f %d %d", 
    &numero_atomico, &abreviacao, &nome, &massa_atomica, &grupo, &periodo);

printf()有同樣的問題


  • 限制字符串的輸入寬度

  • 檢查scanf()的返回值。


int numero_atomico;
//char abreviacao;
char abreviacao[4];  // Some elements need 3 letters.
char nome[20];
float massa_atomica;
int grupo;
int periodo;

// while(!feof(tabela))
while(fscanf(tabela, "%d %3s %19s %f %d %d", 
    &numero_atomico, abreviacao, nome, &massa_atomica, &grupo, &periodo) == 6) {
  printf("%d - %s - %s - Massa atomica: %0.3f - Grupo: %d - Periodo: %d\n", 
      numero_atomico, &abreviacao, &nome, massa_atomica, grupo, periodo);
}
// rewind(tabela); // not needed

還推薦使用double massa_atomica

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM