0

I am new at C programing, and i was asked to build a simple line splitter, that receives a sentence input from the user (in the stdin), and print it again in the stdout (without saving the whole sentence) and skips one line ("\n") if "@" or "*" were typed in. (also they want each sentence to start with its line number). I completed the program and it works great, except one little thing: for every input I try the first letter is lost. the rest is done as I was required.

can anyone tell me what is wrong?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>


int main(int argc, char **argv) {
    char cInput;
    int i = 1;
    int moreData = 1;

    printf( "line_splitter, please enter a sentence:\n");
    fflush(stdout); 
    cInput = fgetc(stdin);
    printf("%c: ", i);
    i=i+1;


/*while not end of file read to avoid error*/   
    while(!feof(stdin) && moreData){
    cInput = fgetc(stdin);
    fputc(cInput,stdout);
    switch(cInput){
        case '@':
        case '*':
            printf("\n");
            printf("%d: ", i);
            i=i+1;
        break;
        case '\n':
            moreData = 0;
        default:
            break;
    }
     }
     printf( "\ndone!\n");

  return 0; 
}

EDIT: thank you all, i made it :)

lolu
  • 370
  • 4
  • 20

1 Answers1

1

Immediately after you use fflush, you read a character. That character is never printed/processed. Remove that read and then update your while loop to

while((cInput = fgetc(stdin)) != EOF && moreData)

Make sure you redeclare cInput as an int which is the correct return type from fgetc.

DrC
  • 7,528
  • 1
  • 22
  • 37
  • 1
    And remove the `fgetc` in the `while` loop. – Spikatrix Mar 16 '15 at 15:44
  • the while loop change you said i did, but when i changed cInput to int, it didnt print my sentence as it should =/ – lolu Mar 16 '15 at 16:09
  • I tried the same change and it worked. Only problem I had was I had to fix the printf mentioned above by CG and the "1:" came up on screen too early. – DrC Mar 16 '15 at 18:29