I have a string, which I declare as char myStr[ ] = "5.3 2.4 1.8".
When I print it directly with printf, it seems to print what I would expect. However, when I print each index, instead of getting myStr[3] = ' ' , I get myStr[3] = 32. Below is my code and output. I would like to know why this is happening, and how I can ensure that the spaces will be interpreted as space and not the number 32?
#include <stdio.h>
#include <string.h>
int words(char myStr[ ]);
int main(){
char myStr[ ] = “5.3 2.4 1.8”;
printf(“myStr is: %s\n", myStr);
words(myStr);
}
int words(char myStr[ ]){
int i, length, count=0, prev=0;
length= strlen(myStr);
printf("The length of myStr is: %d\n", length);
for (i=0; i<length; i++){
printf("The %d letter of myStr is: %d\n", i, myStr[i]);
if (myStr[i] != ' '){
if (prev=0)
count++;
else
prev=1;
}
else
prev=0;
}
return count;
}
Below is the output:
The first line is: 5.3 2.4 1.8
The length of myStr is: 11
The 0 letter of myStr is: 53
The 1 letter of myStr is: 46
The 2 letter of myStr is: 51
The 3 letter of myStr is: 32
The 4 letter of myStr is: 50
The 5 letter of myStr is: 46
The 6 letter of myStr is: 52
The 7 letter of myStr is: 32
The 8 letter of myStr is: 49
The 9 letter of myStr is: 46
The 10 letter of myStr is: 56
Thank you for any advice!
%cto interpret it as a character instead of%dwhich will print the ASCII value of the character. Also changeif (prev=0)toif (prev==0).=is the assignment operator, and is different from==, which is the comparision operator."%c"as the format specifier.