How do I read the number of characters from a input in C?

Viewed 915

I am trying to read the number of characters including, the spaces. I use the scanf function to check for chars using %c. Also on a side note, how would I go about storing the input into an array?

#include <stdio.h>

int main(void) {
  char n, count= 0;

  while (scanf("%c", &n) != EOF) {
    count = count+1;
  }  

  printf("%d characters in your input \n", count);

  return 0;
}

When I test input (with spaces) such as abcdefg it doesn't print anything.

3 Answers

Defining a MAX_CHAR and checking that in loop would protect you against invalid memory write. Remember that last byte of an array should be left for '\0', if you want to print or use the char array.

#include <stdio.h>
#define MAX_CHAR 100

int main(void) {

char n[MAX_CHAR]={0}, count= 0;

while((count!=MAX_CHAR-1)&&(scanf("%c",&n[count])==1))
{
    if((n[count]=='\n')){
        n[count]=0;
        break;
    }
    count++;
}

printf("%d characters in your input [%s]\n", count, n);

return 0;
}

scanf does return EOF when it reaches the end of the file. But in order for you to see that happening, you should give your program a file input when you call it like this:

./a.out < input.txt

Inside input.txt you could put any text you want. But if you want to work in the command line, you should read until you find a \n

#include <stdio.h>

int main(void) {
  char n, count = 0;
  scanf("%c", &n);
  while (n != '\n') {
    count = count+1;
    scanf("%c", &n);
  }  

  printf("%d characters in your input \n", count);

  return 0;
}

If you want to store the input in an array, you must know the size of the input (or at least the maximum size possible)

#include <stdio.h>

int main(void) {
  char n, count = 0;
  char input[100]; //the max input size, in this case, is 100
  scanf("%c", &n);
  while (n != '\n') {
    scanf("%c", &n);
    input[count] = n; //using count as the index before incrementing
    count = count+1;
  }  

  printf("%d characters in your input \n", count);

  return 0;
}

Furthermore, if don't know the size or max size of the input, you'd have to dynamically change the size of the input array. But I think that would be a little advanced for you right now.

Your printf doesn't print anything because runtime doesn't reach to it. Your code looping for ever in while loop

  while (scanf("%c", &n) != EOF) {
    count = count+1;
  }

because scanf won't return EOF in this case

Related