简体   繁体   中英

convert characters in a string C

I am working on a program to change take a word or multiple words from the user(at most 100 characters). for example if the user put in dakka dakka, they would get d@kk@ d@kk@ printed out. I am doing something wrong and it only prints the first word of what I type.

#include <stdio.h>
#include <string.h>

int main()
{
 char utext[100];
 int i, len;
 char c;

 len = strlen(utext);

 printf("type in your message to be converted: \n");
 fgets( utext, 100, stdin );

 for ( i = 0; i < len; ++i )
  {
  c = utext[i];

  if (c == 'a')
   c = '@';
 printf("%c", c);
  }

return 0;
}

You are calling strlen() on an uninitailized array.

The strlen() function searches for the terminating '\\0' which is not in utext before you call fgets() .

Also, you don't want to iterate over the 100 characters, which would be done if you change strlen() with sizeof() , because that will give you the size of the array in bytes, reason for which

fgets(utext, sizeof(utext), stdin);

is ok, and not just ok, it's better because now you can change the size of the array without needing to alter this line.

For the for loop, I would recommend using two facts

  1. fgets() reads the trailing '\\n' which is inserted by the user when Enter is pressed, and is almost mandatory.

  2. Any valid c string, ie one that would return it's length when passed to strlen() , must have a terminating '\\0' , so if '\\n' is not present for some reason, then '\\0' would be.

From the two points above, the for loop should look like

for (i = 0 ; ((utext[i] != '\n') && (utext[i] != '\0')) ; ++i)
 {
    c = utext[i];
    if (c == 'a')
        c = '@';
    printf("%c", c);
 }

You might consider reading in by characters, then you dont even have to store the string. A code like this would work:

int c;
while((c = getchar()) != EOF)
{
    if(c == 'a')
        printf("@");
    else
        printf("%c", 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