2013-04-10 53 views
-1

我有具有以下數據txt文件:需要轉換值應取爲INT /浮子從文件在C

5 
676.54 
6453.22 
7576.776 
8732.2 
6 

我需要讀取在由線C程序行的文件。但是無論用什麼方法來讀取文件,我都會將該值作爲字符串來獲取。我需要得到的值爲int和float類型(取決於值)。有什麼辦法可以做到這一點?操作平臺是linux。

+0

你嘗試過什麼樣的方法? – teppic 2013-04-10 14:46:26

+0

如果你沒有告訴我們你在做什麼不起作用,沒有辦法解決問題沒有辦法解決問題。 – 2013-04-10 14:49:41

+0

我嘗試過使用fgetc和fgets。以下答案解決了這個問題。 – 2013-04-10 15:12:01

回答

2

使用fscanf()

FILE* f = fopen(name, mode); 
float d; 
fscanf(f, "%f\n", &d); 

但是,這總是會給你浮動(使用%lf爲雙打)。

如果你想知道格式是以字符串的形式讀取一行,然後使用strtod()嘗試先讀取它作爲一個int,並看看有多少字符串被使用(如果全部,它是一個int)和strtod()以雙精度讀取。

+0

「如果沒有size修飾符,應用程序應確保相應的參數是指向** float **的指針。」 - http://pubs.opengroup.org/onlinepubs/009695399/functions/fscanf.html – Sebivor 2013-04-10 14:58:13

+0

'「%f」'是「double」的正確格式(或至少是「a」)。沒有'float'的格式,因爲如果你試圖將一個'float'傳遞給'printf',它會在'printf'接收它之前被提升爲'double' http://stackoverflow.com/questions/ 4264127 /正確的格式說明符換雙合的printf/4264154#4264154 – MOHAMED 2013-04-10 15:39:26

0

逐行讀取文件線作爲浮動X

如果X == ((int) X)那麼它的int

否則這是一個float

float X; 
int a; 
while(fscanf(file, "%lf", X)>0) { 

    if(X == ((int) X)) { 
     a = ((int) X); 
     printf("scanned value is integer: %d\n", a); 
    } else { 
     printf("scanned value is float: %lf\n", X); 

    } 

} 
1

如果你想讀浮點數使用fscanf%f%的代碼

float var; 

while (fscanf(yourfilepointer, "%f", &var) == 1) 
{ 
    // do your stuff with your float var 
} 
0
#include <stdio.h> 
#include <stdlib.h> 

typedef union _num { 
    long int integer; 
    double floating; 
} NumberU; 

typedef struct _n { 
    char type; 
    NumberU data; 
} Number; 

int main() { 
    FILE *fp; 
    int c,i; 
    char buff[16]; 
    Number num[10]; 

    fp=fopen("data.txt","r"); 
    for(c=0;c<10 && NULL!=fgets(buff,sizeof(buff),fp);){ 
     char *ck; 
     long di; 
     double dd; 
     di=strtol(buff, &ck, 0); 
     if(*ck == '\n'|| *ck == '\0'){ 
      num[c].type = 'i'; 
      num[c++].data.integer = di; 
      continue; 
     } 
     dd=strtod(buff, &ck); 
     if(*ck == '\n'|| *ck == '\0'){ 
      num[c].type = 'f'; 
      num[c++].data.floating = dd; 
      continue; 
     } 
     fprintf(stderr, "error input:%s\n", buff); 
    } 
    fclose(fp); 

    for(i=0;i<c;++i){ 
     if(num[i].type=='i') 
      printf("%ld\n", num[i].data.integer); 
     else if(num[i].type=='f') 
      printf("%lf\n", num[i].data.floating); 
    } 

    return 0; 
}