Search code examples
cgetsputsfputs

First letter of any word after the first goes missing


I am fairly new to programming and i have done some in school, but they only taught basic functions like printf, scanf, for, while, pointers. I am making a small program that will print user input in to a file, but when the text is written into the file the first letter of every word after the first is missing and i don't know why. can somebody explain what is happening to the first letters and do so in a simple manner if you can, please and thank you for your answer.

This is the function i am using to write to the file.

void text(){
    int e=1;        
    puts("After a sentance press enter to continue or esc to stop");` 
    printf("Enter text now\n");
    FILE *fp;
    fp=fopen("Text.txt","w");
End:while(e==1){
    char txt[100];
    puts(gets(txt),fp);
    if(getche()=='\e')
    e=0;
    goto End;   
    }   //end of while
        fclose(fp);
    }// end of function

New code

void text(){
    int e=1;        
    puts("After ending a sentance press enter to continue or esc to stop"); 
    printf("Enter text now\n");
    FILE *fp;
    fp=fopen("Text.txt","w");
while(e==1){
    char txt[100];
    fgets(txt,100,stdin);
    fwrite(txt,sizeof(char),sizeof(txt),fp);
    if(getche()=='\e'){
        break;
    }
    else;   
    }   
        fclose(fp);
    }

Solution

  • Your code has many issues, but... your particular problem is that getche() reads one character, if it is \e you do something, but if it is another characters, then it is lost!

    Using your functions of choice (getche() and gets()) you can do:

    while (1)
    {
        char c = getche();
        if (c == '\e')
            break;
        txt[0] = c;
        gets(txt+1);
        /* ... */
    }
    

    This will not remove the first character, but will fail with empty lines, I think.. I will leave that as an exercise to the reader.