簡體   English   中英

如何使用sscanf從字符串(從文件讀取)直接輸入整數值?

[英]How to directly input integer values from string (read from file) using sscanf?

我正在嘗試編寫一段代碼,以讀取PPM文件的“標題”。 例如:

P3
400 200
255

在這種情況下,寬度為400,高度為200,最大顏色值為255。我試圖將這些字符串值分配為整數,但我認為有一種更好的方法來減少行數和更“安全”。 ” 如何避免必須使用atoi()函數? (請注意,我已經在“ ACTUAL”代碼中添加了“檢查文件是否可打開部分,這只是減少的代碼段)”

  char buffer[200];
  char height[200];
  char width[200];
  char maxColour[200];

  FILE *file = fopen("mcmaster.ppm", "r");

  fgets(buffer, sizeof(buffer), file); // File format line

  fgets(buffer, sizeof(buffer), file); // Width x height line
  sscanf(buffer, "%s %s", width, height);

  fgets(buffer, sizeof(buffer), file); // Max colour line
  sscanf(buffer, "%s", maxColour);

  int actHeight = atoi(height);
  int actWidth = atoi(width);
  int actMaxColour = atoi(maxColour);

我建議您使用fscanf而不是sscanf。 首先,定義一個“錯誤函數”以驗證讀取文件的問題,如下

void fscanf_Error(char *file)
{
    fprintf(stderr,"Error reading file: %s\n. Exiting(1).\n ",file);
    exit(1);
}

然后

  char dummy[12];
  if(!fscanf(file, "%s\n", dummy))
      fscanf_Error(file);
  if(!fscanf(file," %d %d\n", width, height))
      fscanf_Error(file);
  if(!fscanf(file, "%d\n", maxColour))
      fscanf_Error(file);

暫無
暫無

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

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