I needed to make a program to count the number of words, sentences and letters by getting an input from the user. The program works perfectly until the input i give is multi-lined. If the input is longer than the text that can fit in the terminal window, the program starts to ignore all full stops/question marks/exclamation marks. I don't know why, and I'd like some help. This doesn't happen if the text can fit in one line of the terminal window. I also printed every character when it's read by the program, but that also ignores all full stops/question marks/ exclamation marks. None of those characters get printed. For clarification, a sentence is just the number of full stops/question marks/ exclamation marks, number of words is just the number of spaces in the text plus 1. Here is my code:
#include <stdio.h>
#include <ctype.h> //for the isalpha() function
#include <cs50.h> //for the get_string() function
int main(void)
{
int sentences = 0, letters = 0;
int words = 1;
char character;
string text = get_string("Enter Text: \n");
char x = 0;
while (text[x] != '\0')
{
character = text[x];
switch (character)
{
case ' ':
words++;
break;
case '.':
sentences++;
break;
case '?':
sentences++;
break;
case '!':
sentences++;
break;
default:
if (isalpha(character))
{
letters++;
}
}
x++;
}
printf("\n");
printf("WORDS: %d, LETTERS: %d, SENTENCES: %d\n", words, letters, sentences);
}
I'm fairly new to c, but I have around a year of experience in Python. Thank you for your time.
char x = 0;
toint x = 0;
so it does not overflow on long lines. – Weather Vaneisspace()
andispunct()
too. – Weather Vane