DEN_VER
DEN_VER

Reputation: 69

A program with "getchar/putchar" which takes lines of text and prints it each sentence from a new line

I'm trying to write a simple program using getchar/putchar operators. It must get text in lines and print it out every sentence from the new line.

I wrote this code but it works unexpectedly for me, for example I wrote

"I can't program. Help me. Please."

it prints out:

I can't program.
. Help me.
. Please.

Why it's duplicating "."??? My code is:

#include <stdio.h>
#include <stdio.h>


int main(void) {
    int stop=0;
    int i;
    printf("enter your text:  ");
    while((i=getchar())!=EOF){
        if(i=='.')
        {
            stop=1;
            putchar(i);
            putchar('\n');
        }
        if(i==' ')
        {
            if(stop==0) putchar(i);
        }

        else if(i!=' '||i!='.')
        {
            putchar(i);
            stop=0;
        }
    }
    return 0;
}

Thank you in advance.

Upvotes: 1

Views: 170

Answers (2)

Michel Billaud
Michel Billaud

Reputation: 1826

A but of reformatting would help to understand the error

if(i == '.') {
    stop = 1;                        // part A
    putchar(i);
    putchar('\n');
}

if(i == ' ') {
    if(stop == 0) {                 // Part B
        putchar(i);
    }
} else if(i != ' ' || i != '.') {
    putchar(i);                     // Part C
    stop = 0;
}

When char i contains a dot,

  • part A is executed (and the dot is printed)
  • the test against space fails
  • and then the else part is executed

In the else part, the test always succeeds, because you write an "or" instead of an "and". So the dot is printed again. by part C.

How to fix it : in your problem there are 3 cases (dot, space, others) and you should avoid to express the same comparaison twice.

A possibility is a series of if/else-if/...

if (i == '.') {
     //  process dot
} else if (i == ' ') {
     // process space
} else {
    // process other
}

A better solution is to use a switch

switch (i) {
case '.':
      // process dot
      break;
case ' ':
      // process space
      break;
default:
      // process other
      break;
}

Upvotes: 1

unwind
unwind

Reputation: 399803

This:

else if(i!=' '||i!='.')

makes no sense, you meant

else if(i != ' ' && i != '.')

Upvotes: 0

Related Questions