0

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;
}
2
  • 2
    use strlen only after you have read the string. Commented May 25, 2015 at 16:59
  • Change fgets( utext, 100, stdin ); to if (NULL==fgets( utext, sizeof(utext), stdin)) return -1; Commented May 25, 2015 at 17:08

2 Answers 2

1

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, i.e. 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);
 }
Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

3 Comments

getchar does not return NULL or a char. It returns an int the character value read, or EOF.
You're right, I edited the code. Although I tried it and it worked with char and NULL.
while((c = getchar()) != NULL) gives the compiler warning warning C4047: '!=' : 'int' differs in levels of indirection from 'void *', also a char won't hold EOF without truncating it to 0xFF making it indistinguishable from the char 0xFF.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.