I can print out the string values of what I read, but I am having trouble converting to use their ASCII equivalent

945 views c
9

I am trying to read a few lines from a file and store the ASCII value of each character read as I go line by line. My input looks like this:

input

Here is what my code originally looked like and what it produced:

char buf3[256], buf5[256], buf6[256], buf7[256], buf4[256], buf9[256];
    fscanf(fp, "%[^\n]", buf3);
while (!feof(fp)) {
    fscanf(fp, "%s %s %s %s %s", buf4, buf5, buf6, buf7, buf9);
    printf("\n%c %c %c %c %c", *buf4, *buf5, *buf6, *buf7, *buf9);
}

result

I thought printing out %c would give me the ASCII value. Is there a way to convert these values?

answered question

You need to use %d to print out the ASCII value of a character - example: printf("%d",buf5[0]); + learn how to access each character of a string.

*buf4, *buf5, *buf6, *buf7, *buf will print the first character in each array. (the %d conversion is correct to print the ASCII value -- to convert to decimal value you would subtract '0' from the character value) You will want to look at Why is while ( !feof (file) ) always wrong?.

2 Answers

6

I thought printing out %c would give me the ASCII value ? No, the format specifier %c prints equivalents char value, since buf4, buf5..etc are char array, so when you prints *buf5 it prints first char of array & if you print ascii value of that, you have to subtract it from 48(ASCII value of 0) if *buf contains digits(0 - 9). For e.g

printf("%d\n",(*buf4)  - 48);  

Or

printf("%d\n",(*buf4)  - '0'); 

Also for this particular case its wstage of stack memory to declare five char array like buf3,buf4..buf9. you can use just one char array & do the operation. For e.g

int index = 0 ;
char buf[20]; /* lets say each word of file are length of 20 char, you can change it */
while (fscanf(fp,"%s",buf) != EOF) {
        while(buf[index] != '\0') {     
                if(buf[index] >= '0' && buf[index] <= '9') { /*or use isdigit() */
                        printf("%d",buf[index] - 48);
                }
                else { /* apart from 0,1,...9 */
                        printf("%d",buf[index]);
                }
                index++;
        }
        printf(" ");
        index = 0;
}

Also read why its wrong to use feof() here

posted this
12

Let's suppose your input 011R0 is stored in array buf then to print ASCII value of each character, you'll have to access each character and print it as if you are printing an integer:

  int i;
  while(buf[i])
   {
       printf("%d\n",buf[i]);
       ++i;
   }

By using indices [i] one can access each character if the string. Besides that have a look at this: Why is “while ( !feof (file) )” always wrong?

posted this

Have an answer?

JD

Please login first before posting an answer.