简体   繁体   中英

'N' character appears in the end of the string

I'm new in C and I'm dealing with an issue when trying to input a string. More specifically, when printing the string the character 'Ν' appears in the end of it and as a result, I cannot measure the exact numbers of characters. Here is my code:

int main()
{
    int j = 0;
    char c[15];
    printf("Give surname: ");
    scanf(" %s", c);
    for (int i = 0; i<sizeof(c) / sizeof(c[1]); i++)
    {
        if (isalpha(c[i]))
        {
            printf("%c ", c[i]);
            j++;
        }
    }
    printf("\nNumber of characters: %d", j);

    return 0;
}

For example: If the input is "john" then I get the following output:

在此处输入图片说明

What am I doing wrong?

That is because you are using sizeof operator on array of chars which is longer than the actual string. You can use strlen from string.h as stated above, or simply iterate over chars till the \\0 , just like that:

char * p = c;
while(*p++)
    if (isalpha(*p))
        printf("%c ", *p);

And if you are interested in number of chars you can just substract the pointers.

Your loop limit is wrong. It is causing you to evaluate indeterminate data. Things specifically wrong:

  • Not checking for success of scanf
  • Not specifying a length-limited format string to avoid overflowing the c[] array.
  • As mentioned, iterating the entire array rather than just the data you assume was read successfully.

All of these can be fixed, some of them trivially.

  • Check that scanf returned 1
  • As your c array is 15 characters, and space must be accounted for the terminating nullchar, use %14s for your format string
  • Either use strlen as the limit of your for (in some fashion, be it saved to a temporary or directly in the conditional clause) or use a pointer.

Regarding the last item, I prefer the latter, as you're only scanning the string once . strlen will scan the string to find the terminator, thereby calculating the length and returning it. Scanning it again during iteration then ensues. You can eliminate the strlen scan by simply not using it, rather using a pointer instead, and stopping scanning when the terminator is discovered.

Rewritten, this is the result:

#include <stdio.h>
#include <ctype.h>

int main()
{
    char c[15];
    int j = 0;

    printf("Give surname: ");
    if (scanf("%14s", c) == 1)
    {
        for (const char *p = c; *p; ++p)
        {
            if (isalpha(*p))
            {
                printf("%c ", *p);
                ++j;
            }
        }

        printf("\nNumber of characters: %d", j);
    }

    return 0;
}

Input

123john456

Output

j o h n
Number of characters: 4

Try using the strlen() function instead. It checks for the null-termination character at the end of your actual string (as opposed to the full array, which may contain garbage characters after the null-termination character).

int length = strlen(c);
for (int i = 0; i < length; i++){

Remember to #include <string.h>

See it in action here: https://repl.it/repls/SugaryUnfoldedCleaninstall

If you're wondering why you need to rely on a function to do this, have a look at the source of strlen() . Writing a function like this that performs well and is correct in all cases is harder than it looks.

Further Reading
How to iterate over a string in 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