Reputation: 1
im very new to C programming, and i am looking for the simplest possible solution to getting scanf to recognise no input, by that i mean pressing the enter key with nothing typed and it knowing nothing has been entered and returning to the main menu. Iv looked about on here and i found a similar problem but scanf was taking an integer value, whereas i require a string for a filename. My code is:
FILE *Fpacket;
char filename[20];
puts("Please declare a name for the file"); // request filename
scanf("%s", filename); // store text in filename string
I have tried a combination of fgets, getchar and afew others but i just cant get it to take the newline character as input. I am aware scanf ignores preceding whitespace, any help greatly appreciated!
Thanks
Upvotes: 0
Views: 886
Reputation: 153447
There is no solution using %s
in scanf("%s", filename)
as the format specifier consumes whitespace, including \n
before attempting to fill filename
. scanf()
will not return until non-whitespace (or EOF or IO Error) occurs.
Much better to use fgets()/sscanf()
char buf[MAXPATH + 2];
if (fgets(buf, sizeof buf, stdin) == NULL) handle_EOF_IOError();
if (buf[0] == '\n')
handle_OnlyEnterKeyPressed();
else
sscanf(buf, "%s", filename);
Upvotes: 2
Reputation: 1
If you want to take a Newline(Enter) character from the keyboard as input, then you need to use another key to terminate the string //press Esc to terminate the string.
int main() {
char filename[20];
char ch;
int i;
i=0;
while ((filename[i] = std::cin.get()) != 27 && i<20) {
i++;
}
return 0;
}
If you press enter on your keyboard, it will take it as character and store it on filename[i], the while loop will never terminate until you press Esc or i<20
Upvotes: -1