簡體   English   中英

讀取文件中的令牌時遇到麻煩

[英]trouble reading tokens in a file

我正在做作業,需要從輸入文件中讀取。 該程序只是退出錯誤,但是,我不知道為什么。 這是我的代碼。

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

int main()
{
  FILE *fp = fopen( "input.txt", "r");
  FILE *outputF = fopen( "output.txt", "w");
  if( !fp || !outputF){
    fprintf(stderr, "can't open files for input/output");
    exit(EXIT_FAILURE);
  }

  char line[250];
  double factor;
  int expo;

  while( fscanf( fp, "%f%d", factor, expo) == 1){
    if( factor == 0){
       fprintf(outputF, "%s\n", "undefined");
    }
  else{
      double total = 1;
      for(int i = 0; i < expo; i++){
        total = total * factor;
      }
      fprintf(outputF, "%f", total);
  }
 }
 fclose(fp);
 fclose(outputF);

 return EXIT_SUCCESS;
} 

我認為問題出在“ while”行,但是我也嘗試了以下代碼,但沒有成功。 輸入文件中有一個doulbe和一個用空格分隔的整數。 即“ 2.33 3”

while(fscanf(fp, "%s", line) == 1){
 char *token;
  token = strtok(line, " ");
  float factor;
  sscanf(token, "%f", &factor);
  token = strtok(NULL, "\n");
  int expo;
  sscanf(token, "%d", &expo);
  1. while (fscanf( fp, "%f%d", factor, expo) == 1)問題是

     while (fscanf(fp, "%f%d", &factor, &expo) == 2) 

    閱讀fscanf()的手冊。 它不返回真值,而是返回字符串中匹配的說明符數。

  2. 第二個問題,由於不正確的scanf()格式說明符而導致的未定義行為 ,對於double您需要"%lf"而不是"%f"

  3. 第三個問題,必須傳遞要讀取的值的地址,以允許scanf()將結果存儲在這些變量中,這就是&在上面固定的fscanf()中所做的事情。


注意 :您的編譯器應警告這些錯誤中的兩個,錯誤的格式說明符,並且不對這些特定說明符使用運算符&地址。 有兩個選項,您可以忽略這些警告,或者在關閉警告的情況下進行編譯。 這些可能的原因中的第一個確實很糟糕,請不要忽略警告。 第二,閱讀您的編譯器的文檔並啟用盡可能多的診斷程序,以避免愚蠢的錯誤。

暫無
暫無

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

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