Search code examples
cinputscanftxtfgetc

Read integers AND characters from file line by line in C


I have a txt file of this form:

11
10
BU
1U
0U
0U
...

I would like to read each digit/character one by one from the file in C. The first two rows contain 2 integers, the rest of the rows contain first a letter/integer and then a letter. I unfortunately do not know how to realize this since you can't know if what you read is an integer or a character.

Could someone help me with this?


Solution

  • Here is a minimal exaple on how to address every single character in your file and transforming into integer if one is met. I am sure you could try and adapt this code to your needs. The code in addition jumps newlines and EOF.

    To better understand how this works have a look at the standard ASCII.

    #include<stdio.h>
    
    
    int main(){
      FILE * handle;
      handle = fopen("data.txt","r");
      char var;
    
      while(var!=EOF){
        var=fgetc(handle);
        if(var>47&&var<58){
          printf("Value: %d",var);
          printf(" Integer: %d \n",var-48);
        }
        else if(var!=10 && var!=-1){
          printf("Value: %d",var);
          printf(" Char or other: %c\n",var);
      
        }
      }
     
    }
    
    

    Output:

    Value: 49 Integer: 1 
    
    Value: 49 Integer: 1
    
    Value: 49 Integer: 1
    
    Value: 48 Integer: 0
    
    Value: 66 Char or other: B
    
    Value: 85 Char or other: U
    
    Value: 49 Integer: 1
    
    Value: 85 Char or other: U
    
    Value: 48 Integer: 0
    
    Value: 85 Char or other: U
    
    Value: 48 Integer: 0
    
    Value: 85 Char or other: U