Hello im working on a C program that counts the number of tabs, blanks and newlines. Here is my code:
#include <stdio.h>
#define MAXLENGTH 500
/* This program accepts a string as input.
* It should then count blanks, tabs and newlines.
* It should print out the number of each seperately on a new line.
*/
int main()
{
char s[MAXLENGTH]; /*Array which is the string*/
char *sp = &s[0]; /*Pointer for address of first element in s[]*/
char c; /*Contains the current character being checked */
int i; /*Used as an incrementor to traverse the array*/
int i_bl, i_tb, i_nl; /*Stores the number of blanks, tabs and newlines in these counting variables*/
i_bl = i_tb = i_nl = 0; /*Assigns the initial value of the counting variables*/
scanf("%s", sp);
printf("%s\n", s); /*Testing the string was infact inputted
for (i = 0; c != '\0'; i++)/*Traverses the character string until EOF*/
{
c = s[i]; /*Stores the current character*/
switch(c) /*For blanks, tabs and new lines this incremements the appropriate counting variable*/
{
case ' ': i_bl++; break;
case '\t': i_tb++; break;
case '\n': i_nl++; break;
default: break;
}
}
printf("%d\n%d\n%d\n", i_bl, i_tb, i_nl);
return 0;
}
My problem is that it just isn't counting. The output always reads 0 0 0.
Also when I input 'Hello ', it doesnt print any of the blank spaces after hello.
So yeah, help on making it work and advice on a better way to input strings please.