简体   繁体   中英

How to take input from a file using a C program?

I have to take input from a file and convert the number from kelvin to fahrenheit(vice versa), using a "C" program.

Requirements:

  1. The conversion and numeric outputs must take place in the compiled program.
  2. The script will give the user an option to convert either kelvin to fahrenheit or fahrenheit to kelvin.
  3. Numbers need to be rounded to the nearest tenth.

Input file:

0
32
100
212
108
1243
3000
85  
22
2388
235

Output File:

Fahrenheit Temperature     Kelvin Temperature  
  0                           256    
  32                          273  
  100                         310    
  212                         373    
  108                         315    
  1243                        945    
  3000                        1921  
  85                          302  
  22                          268  
  2388                        1581  
  235                         385  

"C" Program:

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

int main(int argc, char *argv[])  
{  
    //assign the variables used in this program  
    int temp, conv_temp, conv_type;  

    //assign the input options to variables
    conv_type = atoi(argv[1]);  
    temp = atoi(argv[2]);  

    //convert the temps  
    // if input number is 1, then convert from kelvin to fahrenheit    
    // if input number is anything else, convert from fahrenheit to kelvin    

    if(conv_temp == 1)  
        conv_temp = (((temp - 273) * 1.8) + 32);  
    else  
        conv_temp = ((((temp - 32) *5) / 9) + 273);  

    //print the data    
    printf("    %3.1i    %3.1i\n",temp, conv_temp);

    //end of main function  

    return 0;  
}

You have several issues here.
First: you declare "conv_type" and initialize it, but fail to do anything with it.

conv_type;
conv_type = atoi(argv[1]); 

Second: before you give a value for "conv_temp" you are attempting to use it in an if statement.

if(conv_temp == 1)  
        conv_temp = (((temp - 273) * 1.8) + 32);  
    else  
        conv_temp = ((((temp - 32) *5) / 9) + 273); 

Third: in the problem statement, you state you have to do file I/O.
Here is a link to a tutorial on file IO in C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM