1

I was making a code and I want to take the first character of the string and edit it out, but the code is not working like it should:

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

#define MAX_lIMIT 100

int main() {
    char link[MAX_lIMIT];
    int length;
    int codex;

    scanf("%s", link);
    printf("%s, Write the new version of the script.\n", link);
    length = strlen(link);
    printf("%c", link[0]);

    scanf("%c", &link[0]);
    printf("%c", link);
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • ***How*** "is it not working as it should"? Please take some time to read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please [edit] your question to include the expected behavior, and the actual behavior. Including showing us some specific input, and the expected and actual output for that input. – Some programmer dude May 29 '20 at 11:10
  • 1
    Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). – Weather Vane May 29 '20 at 11:15
  • Also `printf ("%c", link);` is incorrect, it should be either `printf ("%s", link);` or `printf ("%c", link[0]);` – Weather Vane May 29 '20 at 11:16

1 Answers1

0

When scanf("%c", &link[0]); reads the next byte from stdin, it gets the pending newline left by the previous call scanf("%s", link);.

You should use scanf(" %c", &link[0]); to first skip any white space and read the next character.

There are other problems in your code:

  • MAX_lIMIT should probably be MAX_LIMIT
  • scanf("%s", link); may overflow the destination array if more than 99 characters are typed without whitespace. Use scanf("%99s", link);
  • always test the return value of scanf()
  • printf("%c", link[0]);` should probably also print a newline for the output to be visible to the user.
  • printf("%c", link);is incorrect, it should beprintf("%s\n", link);`

Here is a modified version:

#include <stdio.h>

#define MAX_LIMIT 100

int main() {
    char link[MAX_LIMIT];

    if (scanf("%99s", link) != 1)
        return 1;
    printf("%s, Write the new version of the script.\n", link);
    printf("%c\n", link[0]);

    if (scanf(" %c", &link[0]) != 1)
        return 1;
    printf("%s\n", link);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189