0
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char string[100];
    int count=0;

    char *pString = string;

    printf("Enter a string: \n");
    scanf("%s",string);

    while(*pString != '\0')
        count++;

    printf("String is %d characters long",count);


    return 0;
}

Heres my code. I want to write a simple function to count the number of characters in a string array. The problem is it gets stuck after I enter the string. And the console just freezes. It doesn't release the output.

2
  • 6
    you are not incrementing pointer in while loop Commented Sep 21, 2019 at 7:22
  • OT: regarding: scanf("%s",string); 1) always check the returned value (not the parameter values) to assure the operation was successful. Note: the scanf() family of functions returns the number of successful 'format conversion specifiers' (in this case any returned value other than 1 indicates an error. 2) when using '%s' and/or '%[...]' always include a MAX CHARACTERS modifier that is 1 less than the length of the input buffer. This avoids any possibility of a buffer overflow and the attendant undefined behavior Commented Sep 22, 2019 at 15:05

1 Answer 1

1

You could use something like

#include <stdio.h>
#include <stdlib.h>

int main() {
    char string[100];
    int count = 0;

    printf("Enter a string: \n");
    char *pString = fgets(string, sizeof(string), stdin);
    if (pString == NULL) {
        fprintf(stderr, "failure reading from stdin\n");
        exit(1);
    }
    while (*pString != '\0' && *pString != '\n') {
        pString++;
        count++;
    }

    printf("String is %d characters long", count);
    return 0;
}

It uses fgets which also checks for the length of the buffer. fgets returns also the newline that the users enters, therefore an additional check for '\n'. Like in the comments mentioned by arvin also the char pointer needs to be incremented in the loop.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much. I immediately knew my mistake when I saw your code.. I didn't increment the pointer each loop so it just stayed on the first index of the array.. one thing tho.. on my compiler i tried to used fgets using your method. but it gave me an error. can you assign *pString = fgets. i thought you can only put addresses on pointers.
fgets return a pointer to the string (don't forget you supply a buffer as argument). In case something goes wrong (e.g. end-of-file or an error) you get NULL back and the supplied buffer remains unchanged. What error did you get?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.