2015-11-09 24 views
-1

我從我的教授那裏收到了大量任務(最多100個帶符號的字符)和應該添加或減去給定數字的操作。該文件應始終以=結尾。我附上了輸入圖像和輸出。對從文件中讀取的數字進行操作,不起作用

image

我遇到了一個問題。當我在第一行讀取數據並用printf打印出來後,我得到一個看似隨機的數字。該代碼可以發現如下:

#include <stdio.h> 

int main() 
{ 
    long long first, second, result; 
    char operation, operation1; 
    FILE *f; 
    FILE *k; 
    f = fopen("in.txt", "r"); 
    k = fopen("out.txt", "w"); 

    if(f == NULL) { 
     printf("Error in in.txt"); 
     return 1; 
    } 

    if(k == NULL) { 
     printf("Error in out.txt"); 
     return 1; 
    } 

    fscanf(f, "%lli\n", &first); 
    fscanf(f, "%c\n", &operation); 
    fscanf(f, "%f\n", &second); 
    fscanf(f, "%c", &operation1); 
    printf("%lli",&first); 
    switch(operation) { 
     case '+': 
      result=first+second; 
     break; 
     case '-': 
      result=first-second; 
     break; 
    } 
    switch(operation1){ 
     case '=': 
     fprintf(k, "%.1", result); 
    } 

    fclose(f); 
    fclose(k); 
    return result;  
} 

出於某種原因,如果我先申報,只要它會打印出不同的號碼,如果我把它聲明爲整數寫入了第三個。謝謝!

+0

什麼是輸入文件('in.txt')是什麼樣子?另外,'%lli'用於'long long int'。 – lurker

+0

您能否提供您嘗試過的結果的樣本編號? –

+0

我已經上傳了一張圖片。它被稱爲「圖像」,但由於某種原因,它不會顯示縮略圖。 –

回答

0

你的問題是與printf語句

printf("%lli",&first); 

這將打印變量而不是地址的值。

printf("%lli",first); 

這應該先打印long變量的值。

演示: http://goo.gl/QPCLWZ