Rj Lopez
Rj Lopez

Reputation: 1

How do I correctly store a string input in to character array using pointers?

#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.

Upvotes: 0

Views: 61

Answers (1)

Stephan Schlecht
Stephan Schlecht

Reputation: 27126

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.

Upvotes: 1

Related Questions