0

When I execute my code below. It waits for my input for entering a file name. But it doesn't wait for me to enter a filename, but rather just skips it to the _getch() part of it. I'm unable to add a sentence.

Code not working:

#include <stdio.h>

main() {

    FILE *fp;
    char fnamer[100] = "";      //Storing File Path/Name of Image to Display
    printf("\n\nPlease Enter the Full Path of the Image file you want to view: \n");
    scanf("%s", &fnamer);
    fp = fopen(fnamer, "w");
    if (fp == NULL)
    {
        printf("\n%s\" File NOT FOUND!", fnamer);
    }
    char c[1000];
    printf("Enter a sentence:\n");
    gets(c);
    fprintf(fp, "%s", c);
    fclose(fp);
    _getch();
}

Code that works and waits for entering a sentence:

#include <stdio.h>
#include <stdlib.h>  /* For exit() function */
int main()
{
    char c[1000];
    FILE *fptr;
    fptr = fopen("program.txt", "w");
    if (fptr == NULL){
        printf("Error!");
        exit(1);
    }
    printf("Enter a sentence:\n");
    gets(c);
    fprintf(fptr, "%s", c);
    fclose(fptr);
    return 0;
}

Both are so similar right there in the end for the prompt asking for a sentence. It doesn't make sense.

LPs
  • 16,045
  • 8
  • 30
  • 61
Ansh
  • 175
  • 1
  • 2
  • 13
  • 1
    Probably not related, but remove the ampersand: `scanf("%s", &fnamer);` -> `scanf("%s", fnamer);` – Eugene Sh. Sep 28 '16 at 14:34
  • 2
    [why-is-the-gets-function-so-dangerous-that-it-should-not-be-used](http://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – LPs Sep 28 '16 at 14:36
  • `scanf` is complicated to use and useless if the input does not match the scanf format string. Rather use `fgets`. – Jabberwocky Sep 28 '16 at 14:47

4 Answers4

0

you have to flush your input after using scanf.

put a getchar() after every scanf

a.costa
  • 1,029
  • 1
  • 9
  • 19
  • Error message: Error 3 error LNK2019: unresolved external symbol __getchar referenced in function _main – Ansh Sep 28 '16 at 15:29
0

You are encountering a very common problem when using stdin to receive input, which is after your first scanf call there is a dangling \n character which gets stuck in the buffer from the enter key. To clear this buffer in a portable easy way, add something like

char c;
while ( (c = getchar()) != '\n' && c != EOF ) { }  

This simply initializes a character, and then calls get char as many times as needed until it reaches '\n' or 'EOF', which is immediately in your case.

tl;dr : Your buffer looks like this

hello.txt\n <-- "comes from the enter key"

and when you try to use get(c) it takes the \n as the next enter key.

0

The rule is never mix scanf and [f]gets. scanf stops before the next unused character, generaly a blank, and the end of line is composed of blank characters.

You could try to put a dummy fgets between the last scanf and the first real fgets. That will ensure that you are now positionned on a beginning of line before reading. Alternatively, you could read everything in lines with fgets, and parse the lines with sscanf. That is what I prefere as soon as I want my input to be line oriented. And always control return values of input functions, it will avoid a progam suddenly going mad without any indication simply because one input gave an ignored error.

And last and not least: never use gets but only fgets, the former is for decades in the hall of shame as the cause of uncountable buffer overflows

Code could become:

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

main() {

    FILE *fp;
    char fnamer[100] = "";      //Storing File Path/Name of Image to Display
    char c[1000], *ix;
    int cr;
    printf("\n\nPlease Enter the Full Path of the Image file you want to view: \n");
    cr = scanf("%s", &fnamer);
    if (cr != 1) {
        // process error or abort with message
    }
    fp = fopen(fnamer, "w");
    if (fp == NULL)
    {
        printf("\n%s\" File NOT FOUND!", fnamer);
        return 1; // do not proceed after a fatal error!
    }
    for(;;) {  // read until a newline in input
        ix = fgets(c, sizeof(c), stdin);
        if (ix == NULL) {
            // end of input: abort
        }
        if (strcspn(c, "\n") < strlen(c)) break;
    }
    printf("Enter a sentence:\n");
    ix = fgets(c, sizeof(c), stdin);
    c[strcspn(c, "\n")] = '\0'; // remove end of line to get same data as gets
    fprintf(fp, "%s", c);
    fclose(fp);
    _getch();
}
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0
main() {

  FILE *fp;
    char fnamer[100]="";        //Storing File Path/Name of Image to Display
    printf("\n\nPlease Enter the Full Path of the Image file you want to view: \n");
    fgets ( fnamer,100,stdin); //fgets(name, sizeof(name), stdin);
    fp=fopen(fnamer,"w");
            if(fp==NULL)
        {
            printf("\n%s\" File NOT FOUND!",fnamer);
            getch();
            exit(1);
        }

}

I Think best way to do,use fgets insted of scanf,Because fgets() can read any open file, but scanf() only reads standard input(user given).

fgets() reads a line of text from a file; scanf() can be used for that but also handles conversions from string to built in numeric types

Sachith Wickramaarachchi
  • 5,546
  • 6
  • 39
  • 68