Logical Error in my C Code - c

I am a beginner, just learning C; so, please be patient with me.
I am trying to write a very simple program that goes through a string, counts the characters in each word, and then replaces those words with the number of their characters. My problem is that I am stuck in an infinite loop and cannot figure out why! Here is the code:
#define NEWLINE '\n'
#define SPACE ' '
int main(int argc, char *argv[]) {
int character;
int count = 0;
printf("\nType in a sentence of any lenght, then hit ENTER!\n");
character = getchar();
while (character != NEWLINE) {
while ((character != SPACE) || (character != NEWLINE)) {
count++;
character = getchar();
}
printf("%d ", count);
count = 0;
if (character != NEWLINE) {
character = getchar();
}
}
printf("\n");
system("PAUSE");
return 0;
}
Thanks for everyone who helped me! I guess I go back and study logical operators a bit more.

while ((character != SPACE) || (character != NEWLINE)) {
count++;
character = getchar();
}
this will loop infinitely because the inverse:
(character == SPACE) && (character == NEWLINE)
will ALWAYS be false.
I suspect you mean
while ((character != SPACE) && (character != NEWLINE)) {
count++;
character = getchar();
}

You have an always true condition:
(character != SPACE) || (character != NEWLINE)
eg:
character = ' ': false or true => true
character = '\n': true or false => true
You should change it to:
(character != SPACE) && (character != NEWLINE)
That should fix your infinite loop.

Replace the || With &&

Replace the || (OR) with && (AND) because the while loop will always be true and for that reason it will never break out of the loop. It should work if you replace it.

Related

The answer outputs blanks

Program task -
Enter a string, display it word for word on the screen.
The problem is that if you type a lot of spaces between words, they will show up when you check. How can this be fixed?
#include <stdio.h>
int main()
{
int inw = 0, i = 0, count = 0;
char s[10000];
printf("Print string (max 10000 sb):\n");
gets(s);
while (s[i] != '\0') {
if (s[i] != ' ' && s[i] != '\t') {
putchar(s[i]);
}
else if (s[i] == ' ') {
printf("\n");
}
i++;
}
return 0;
}
Ugly, but this gets the job done. Just need a flag to keep track of whether or not you just printed a new line. Also cleaned up unused variables and changed to using fgets
#include <stdio.h>
#include <stdbool.h>
int main()
{
int i = 0;
char s[10000];
bool justPrintedNewline = false;
printf("Print string (max 10000 sb):\n");
fgets(s, sizeof s, stdin);
while (s[i] != '\0') {
if (s[i] != ' ' && s[i] != '\t') {
putchar(s[i]);
justPrintedNewline = false;
}
else if (s[i] == ' ' && justPrintedNewline == false) {
printf("\n");
justPrintedNewline = true;
}
i++;
}
return 0;
}
Demo
You did a great job in the algorithm just fix a little thing.
You can create a flag and after space you increase the flag to 1.
Then you will know you will print just one space.
After printing " " check for a char that isn't " " for update the flag to 0.
When the flag is 1 DONT print anything just wait for another valid char.
Take care,
Ori
Only print a line-feeed when starting a word and after all is done.
Change code to:
If a space
-- print a '\n' when the prior character is a non-white-space.
Else
-- if (prior character is white-space) print a '\n'
-- print it
char prior = 'a';
while (s[i]) {
char ch = s[i];
if (ch != ' ' && ch != '\t') {
if (prior == ' ' || prior == '\t') {
putchar('\n');
}
putchar(ch);
}
prior = ch;
i++;
}
putchar('\n');
There is a bit of a trick to it: use a second, inside loop to skip past spaces and another to print words. The outer loop should only terminate if you have reached the end of the string.
while (s[i] != '\0')
{
// skip all spaces
while ((s[i] != '\0') && isspace( s[i] )) ++i;
// print the word
while ((s[i] != '\0') && !isspace( s[i] ))
{
putchar( s[i] );
}
// print the newline after a word
putchar( '\n' );
}
By the way, gets() is a really, really dangerous function. It should never have been included in the language. You are OK to use it for a homework, but in reality you should use fgets().
char s[1000];
fgets( s, sizeof(s), stdin );
The fgets() function is a bit more fiddly to use than gets(), but the above snippet will work for you.
Your other option for solving this homework is to use scanf() to read a word at a time from user input, and print it each time through the loop. I’ll leave that to you to look up. Don’t forget to specify your max string length in your format specifier. For example, a 100 char array would be a maximum 99-character string, so you would use "%99s" as your format specifier.

Counting lines, words, and characters

I am a new to programming. I am trying to write a program that reads lines, words and characters from a text file. Here is the code below.
#include "stdio.h"
#include "stdlib.h"
#define IN 1
#define OUT 0
int main (int argc, char *argv[]) {
FILE *input;
int character, newword, newline, state;
char c;
state = OUT;
character = newline = newword =0;
input = fopen(argv[1], "r");
if ( input == NULL){
printf("Error! Can not read the input\n");
exit(-1);
}
while ((c = fgetc(input)) != EOF){
character++;
if (c <'a' && c >'z'){;}
if ( c <'A' && c >'Z'){;}
if (c == '\n'){
newline++;
}
if (c == ' ' || c == '\n' || c == '\t'){
state = OUT;
}
else if (state == OUT){
state = IN;
newword++;
}
}
printf("The number of lines: %d\n", newline);
printf("The number of words: %d\n", newword);
printf("The number of characters: %d\n", character);
fclose(input);
}
I have been trying to figure how not to read special characters such as !, #, #, $, %, ^, &, *, (, ), _, +.
I tried using if statements so it won't read the special characters but it reads it. I think one the if statement for the capital letters is wrong because it probably will not read lower case letters.
In the file the following text is in it,
!!.
and it outputs in terminal:
The number of lines: 2
The number of words: 5
The number of characters: 7
However, if I take out the two for loops (c < 'A' && c > 'Z') and (c < 'a' && c > 'z'), then the output becomes
The number of lines: 2
The number of words: 1
The number of characters: 7
Any hints to fix this problem (I do not want the Answer!)?
Your if must be something like:
if ('a' <= c && c <='z'){character++;}
else if ( 'A' <= c && c <='Z'){character++;}
The easiest way to solve your problem is to increase your character counter when the character is between the interval 'a' and 'z' or the interval 'A' and 'Z', and then, since the escape sequence '\n' creates a new line, this also means that you are dealing with a new word, thus you should increment this counter too. And finally you can check for the space or the horizontal tab to increment the new word counter.
if ((c <'a' && c >'z') || ( c <'A' && c >'Z')){
++character;
}
else if (c == '\n'){
++newline;
++newword;
}
else if (c == ' ' || c == '\t'){
++newword;
}

How to count characters except double or single quotes?

I'm new to programming and learning C through a book.
The author of the book explains about logical operators (AND, NOT and OR) by giving the following example which counts the number of characters except the double or single quotes and period character.
I couldn't understand how it counts the number of characters except the quotes and period character. I understand that with the AND operator both conditions should be true.
#include <stdio.h>
#define PERIOD '.'
int main(void)
{
char ch;
int charcount = 0;
while ((ch = getchar()) != PERIOD)
{
if (ch != '"' && ch != '\'')
charcount++;
}
printf("There are %d non-quote characters.\n", charcount);
return 0;
}
I will try to explain you the main part of the code :
while ((ch = getchar()) != PERIOD)
{
Here, it will check every character contained in your text, as long as the character differ from PERIOD, which is a dot, so it simply check all of the characters in the sentence.
if (ch != '"' && ch != '\'')
charcount++;
}
Here, it adds 1 to the charcount if the condition is true. For the if to return true, both ch != '"' and ch != '\'' must be true ! The && operator is a logical AND, and for an AND to return true (1), both conditions must be equal to 1. So if the character is equal to " or ', the AND will return 0, and so we won't add 1 to the charcount.
This condition if (ch != '"' && ch != '\''), is checking if the entered character is "or ' if not then it increments the count of characters otherwise not. If user enterd d or #, it will satisfy the condition because ASCII value of # is not equal to " or ', and the count will get incremented.
Well, for each char returned by getchar() and stored in ch (from an input stream, like a keyboard or a file) it will test if it's not a double quote (ch != '"') and if it's not a quote (ch != '\'')
\ is an escape character, which means '\'' is the char '
If it's neither of them, then it will increments the counter (charcount++;).
And this will go on as long as getchar() doesn't return a period ((ch = getchar()) != PERIOD)(if it does, the PERIOD won't be counted as the code will step out the will loop immediately).
You can skip using continue:
#include<stdio.h>
#define PERIOD '.'
int main(void)
{
char ch;
int charcount = 0;
while ((ch = getchar()) != PERIOD)
{
if (ch != '"' && ch != '\''){
continue;
}
charcount++;
}
printf("There are %d non-quote characters.\n", charcount);
return 0;
}
Output:
./program
Michi"""LoL'''Another'"LoL.
There are 8 non-quote characters.

Count words from a string

while( (ch = fgetc( infile )) != EOF )
if(ch ==' ') words++;
It works nice, but in case if we have blank lines in a string, how are we suppose to detect these lines and to count thw words right?
Your code does not count words, it counts spaces. In many cases the two counts would be different - for example, when words are separated by more than one space.
You need to change the logic in such a way that you set a boolean flag "I'm inside a word" when you see a character that belongs to a word, and has the following logic when it sees a whitespace character (a space, a tab, or a newline character):
if (isspace(ch)) {
if (sawWordFlag) {
words++;
sawWordFlag = false;
}
}
One way to detect if a character belongs to a word is to call isalnum on it. Both isalnum and isspace functions require you to include <ctype.h> header.
So sscanf already does what you need, it will eat any number of whitespaces before a string including tabs and newlines. This algorithm works with leading or trailing spaces as well.
int words = 0;
int i = 0;
while(sscanf(inFile, "%*s%n", &i) != EOF){
inFile += i;
words++;
}
sscanf is extremely versatile you can easily read out each word as follows:
int words = 0;
int size = strlen(inFile);
if(size > 0){
char* word = (char*)malloc((size + 1) * sizeof(char));
for(int i = 0; sscanf(sentence, "%s%n", word, &i) > 0; sentence += i){
// Do what you want with word here
words++;
}
free(word);
}
char prev = 'x'; // anything but space
while((ch == fgetc(infile)) != EOF)
{
if(ch == ' ' && ch == prev)
continue;
else if(ch == ' ' && ch != prev)
words++;
prev = ch;
}

counting the number of sentences in a paragraph in c

As part of my course, I have to learn C using Turbo C (unfortunately).
Our teacher asked us to make a piece of code that counts the number of characters, words and sentences in a paragraph (only using printf, getch() and a while loop.. he doesn't want us to use any other commands yet). Here is the code I wrote:
#include <stdio.h>
#include <conio.h>
void main(void)
{
clrscr();
int count = 0;
int words = 0;
int sentences = 0;
char ch;
while ((ch = getch()) != '\n')
{
printf("%c", ch);
while ((ch = getch()) != '.')
{
printf("%c", ch);
while ((ch = getch()) != ' ')
{
printf("%c", ch);
count++;
}
printf("%c", ch);
words++;
}
sentences++;
}
printf("The number of characters are %d", count);
printf("\nThe number of words are %d", words);
printf("\nThe number of sentences are %d", sentences);
getch();
}
It does work (counts the number of characters and words at least). However when I compile the code and check it out on the console window I can't get the program to stop running. It is supposed to end as soon as I input the enter key. Why is that?
Here you have the solution to your problem:
#include <stdio.h>
#include <conio.h>
void main(void)
{
clrscr();
int count = 0;
int words = 0;
int sentences = 0;
char ch;
ch = getch();
while (ch != '\n')
{
while (ch != '.' && ch != '\n')
{
while (ch != ' ' && ch != '\n' && ch != '.')
{
count++;
ch = getch();
printf("%c", ch);
}
words++;
while(ch == ' ') {
ch = getch();
printf("%c", ch);
}
}
sentences++;
while(ch == '.' && ch == ' ') {
ch = getch();
printf("%c", ch);
}
}
printf("The number of characters are %d", count);
printf("\nThe number of words are %d", words);
printf("\nThe number of sentences are %d", sentences);
getch();
}
The problem with your code is that the innermost while loop was consuming all the characters. Whenever you enter there and you type a dot or a newline it stays inside that loop because ch is different from a blank. However, when you exit from the innermost loop you risk to remain stuck at the second loop because ch will be a blank and so always different from '.' and '\n'. Since in my solution you only acquire a character in the innermost loop, in the other loops you need to "eat" the blank and the dot in order to go on with the other characters.
Checking these conditions in the two inner loops makes the code work.
Notice that I removed some of your prints.
Hope it helps.
Edit: I added the instructions to print what you type and a last check in the while loop after sentences++ to check the blank, otherwise it will count one word more.
int ch;
int flag;
while ((ch = getch()) != '\r'){
++count;
flag = 1;
while(flag && (ch == ' ' || ch == '.')){
++words;//no good E.g Contiguous space, Space at the beginning of the sentence
flag = 0;;
}
flag = 1;
while(flag && ch == '.'){
++sentences;
flag=0;
}
printf("%c", ch);
}
printf("\n");
I think the problem is because of your outer while loop's condition. It checks for a newline character '\n', as soon as it finds one the loop terminates. You can try to include your code in a while loop with the following condition
while((c=getchar())!=EOF)
this will stop taking input when the user presses Ctrl+z
Hope this helps..
You can implement with ease an if statement using while statement:
bool flag = true;
while(IF_COND && flag)
{
//DO SOMETHING
flag = false;
}
just plug it in a simple solution that uses if statements.
For example:
#include <stdio.h>
#include <conio.h>
void main(void)
{
int count = 0;
int words = 1;
int sentences = 1;
char ch;
bool if_flag;
while ((ch = getch()) != '\n')
{
count++;
if_flag = true;
while (ch==' ' && if_flag)
{
words++;
if_flag = false;
}
if_flag = true;
while (ch=='.' && if_flag)
{
sentences++;
if_flag = false;
}
}
printf("The number of characters are %d", count);
printf("\nThe number of words are %d", words);
printf("\nThe number of sentences are %d", sentences);
getch();
}
#include <stdio.h>
#include <ctype.h>
int main(void){
int sentence=0,characters =0,words =0,c=0,inside_word = 0,temp =0;
// while ((c = getchar()) != EOF)
while ((c = getchar()) != '\n') {
//a word is complete when we arrive at a space after we
// are inside a word or when we reach a full stop
while(c == '.'){
sentence++;
temp = c;
c = 0;
}
while (isalnum(c)) {
inside_word = 1;
characters++;
c =0;
}
while ((isspace(c) || temp == '.') && inside_word == 1){
words++;
inside_word = 0;
temp = 0;
c =0;
}
}
printf(" %d %d %d",characters,words,sentence);
return 0;
}
this should do it,
isalnum checks if the letter is alphanumeric, if its an alphabetical letter or a number, I dont expect random ascii characters in my sentences in this program.
isspace as the name says check for space
you need the ctype.h header for this. or you could add in
while(c == ' ') and whie((c>='a' && c<='z') || (c >= 'A' && c<='Z')
if you don't want to use isalpace and isalnum, your choice, but it will be less elegant :)
The trouble with your code is that you consume the characters in each of your loops.
a '\n' will be consumed either by the loop that scans for words of for sentences, so the outer loop will never see it.
Here is a possible solution to your problem:
int sentences = 0;
int words = 0;
int characters = 0;
int in_word = 0; // state of our parser
int ch;
do
{
int end_word = 1; // consider a word wil end by default
ch = getch();
characters++; // count characters
switch (ch)
{
case '.':
sentences++; // any dot is considered end of a sentence and a word
break;
case ' ': // a space is the end of a word
break;
default:
in_word = 1; // any non-space non-dot char is considered part of a word
end_word = 0; // cancel word ending
}
// handle word termination
if (in_word and end_word)
{
in_word = 0;
words++;
}
} while (ch != '\n');
A general approach to these parsing problems is to write a finite-state machine that will read one character at a time and react to all the possible transitions this character can trigger.
In this example, the machine has to remember if it is currently parsing a word, so that one new word is counted only the first time a terminating space or dot is encountered.
This piece of code uses a switch for concision. You can replace it with an if...else if sequence to please your teacher :).
If your teacher forced you to use only while loops, then your teacher has done a stupid thing. The equivalent code without other conditional expressions will be heavier, less understandable and redundant.
Since some people seem to think it's important, here is one possible solution:
int sentences = 0;
int words = 0;
int characters = 0;
int in_word = 0; // state of our parser
int ch;
// read initial character
ch = getch();
// do it with only while loops
while (ch != '\n')
{
// count characters
characters++;
// count words
while (in_word)
{
in_word = 0;
words++;
}
// skip spaces
while (ch == ' ')
{
ch = -1;
}
// detect sentences
while (ch == '.')
{
sentences++;
ch = -1;
}
// detect words
while ((ch != '\n')
{
word_detected = 1;
ch = -1;
}
// read next character
ch = getch();
}
Basically you can replace if (c== xxx) ... with while (c== xxx) { c = -1; ... }, which is an artifical, contrieved way of programming.
An exercise should not promote stupid ways of doing things, IMHO.
That's why I suspect you misunderstood what the teacher asked.
Obviously if you can use while loops you can also use if statements.
Trying to do this exercise with only while loops is futile and results in something that as little or nothing to do with real parser code.
All these solutions are incorrect. The only way you can solve this is by creating an AI program that uses Natural Language Processing which is not very easy to do.
Input:
"This is a paragraph about the Turing machine. Dr. Allan Turing invented the Turing Machine. It solved a problem that has a .1% change of being solved."
Checkout OpenNLP
https://sourceforge.net/projects/opennlp/
http://opennlp.apache.org/

Resources