How can I catch an enter key ( '\n' )? - c

scanf("%s", input);
if (strlen(input) > 1) {
errorNet();
}
if (input[0] == '\n') {
errorNet();
}
if (input[0] == '\0') {
errorNet();
}
When I hit enter, scanf goes to the next line and continues searching for input. How can I set that if enter is hit, the function errorNet is called?
Ex. If enter/blank line is inputed, call errorNet function.

If you use fgetsyou specify the size of the string you are reading. fgets will stop reading the input when this size is reached or the user pressed \n. Notice that this size counts the \0 in the end of the string.
char input[10];
fgets(input, 10, stdin);
printf("%s\n", input);
To detect if a user just pressed \n without writing anything, just check if the first character is a \n, for example:
if (input[0] == '\n') {
printf("just '\\n'\n");
}

Related

want to insert multiple characters to a file in c(single at a time)

i have been trying to input characters and the character should be put in the file unless users change the value of opt to 'n'.
#include<stdio.h>
void main()
{
char ch,opt='y';
FILE *fp;
fp=fopen("myfile.txt","w");
while(opt=='y' || opt =='Y')
{ scanf("%c",&ch);
fputc(ch,fp);
printf("want to enter more characters(y or n):");
scanf("%c",&opt);
}
fclose(fp);
}
So I want to give the inputs until opt value changes to 'n'.
If you are using Windows OS then you can use following code to read characters without pressing Enter. See here and here to know about reading characters without pressing Enter on Linux plateforms.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch,opt='y';
FILE *fp;
fp=fopen("myfile.txt","w");
while(opt=='y' || opt =='Y')
{
ch = getch();
fputc(ch,fp);
printf("%c\nWant to enter more characters(y or n):", ch);
opt = getch();
printf("%c\n", opt);
}
fclose(fp);
}
Note: You can modify the code if you don't need to print the last entered character. See here to know other variants of getch() function.
Let's say you type a and press Enter.
When you do that, there are two characters in the input stream: 'a' and '\n'. The first scanf reads the 'a' into ch and the second scanf reads the '\n' into opt. That is the source of your problem.
You'll have to write code to read and discard the newline character. Here's one way to do it.
while(opt=='y' || opt =='Y')
{
scanf("%c",&ch);
fputc(ch,fp);
// Assuming that no more than one characte is entered per line,
// read the discard the newline.
fgetc(stdin);
printf("want to enter more characters(y or n):");
scanf("%c", &opt);
// Read and discard the newline again.
fgetc(stdin);
}
If you want to be a bit more flexible about your input, you can use:
// Make it as large as you need it to be.
#define LINE_LENGTH 200
int main()
{
char line[LINE_LENGTH];
FILE *fp;
fp=fopen("myfile.txt","w");
// Read a line of text.
while( fgets(line, LINE_LENGTH, stdin) != NULL )
{
// Print the line to the output file
fputs(line, fp);
printf("want to enter more characters(y or n):");
// Read the entire line again.
if( fgets(line, LINE_LENGTH, stdin) != NULL )
{
// If the entire line is just "n" or "N", break from the loop.
if ( strcmp(line, "n\n") == 0 || strcmp(line, "N\n") == 0 )
{
break;
}
}
}
fclose(fp);
}

C - While-Loop Duplicating Print Statements

When the while-loop runs after the first time, it prints my "Create new node" prompt twice before getting user input from stdin. Why is this? See linked image.
Code:
int main()
{
char userInput[2];
while(1)
{
printf("\nCreate new node? (y/n)\n");
printf(">>> ");
fgets(userInput, 2, stdin);
if(strcmp(userInput, "y") == 0)
{
printf("Yes\n");
}
else if(strcmp(userInput, "n") == 0)
{
printf("No\n");
exit(0);
}
}
}
Terminal Output:
fgets read string plus '\0' plus '\n'. Since userInput is of only 2 bytes, '\n' will not be read by fgets and will be there in the input buffer. On next iteration fgets will read '\n' left by the previous call of fgets.
Increase the buffer size and you will have no problem
char userInput[3];
or you can put
int ch;
while((ch = getchar()) != '\n' && ch != EOF);
just after fgets statement.

Calling scanf() after another string input function creates phantom input

Here's a small program:
#include <stdio.h>
int main() {
char str[21], choice[21]; int size;
while(1){
printf("$ ");
fgets(str, 20, stdin);
printf("Entered string: %s", str);
if(str[0] == 'q') {
printf("You sure? (y/n) ");
scanf("%s", choice);
if(choice[0] == 'y' || choice[0] == 'Y')
break;
}
}
return 0;
}
It reads a string using fgets(). If the string starts with a q, it confirms if the user wants to quit, and exits if the user types y.
When I run it and type q, this happens:
$ q
Entered string: q
You sure? (y/n) n
$ Entered string:
$
Note the $ Entered string:. Clearly, fgets() got an empty character or something as input, even though I didn't type anything.
What's going on?
As described in other answer scanf call leaves the newline in the input buffer you can also use getchar() after scanf like this :
scanf("%20s", choice);// always remember( & good) to include field width
// in scanf while reading
Strings otherwise it will overwrite buffer in case of large strings `
getchar(); //this will eat up the newline
Besides , you should also use fgets like this :
fgets(str,sizeof str, stdin); //Its better
It because the scanf call reads a character, but leaves the newline in the buffer. So when you next time call fgets is finds that one newline character and reads it resulting in an empty line being read.
The solution is deceptively simple: Put a space after the format in the scanf call:
scanf("%s ", choice);
/* ^ */
/* | */
/* Note space */
This will cause scanf to read and discard all training whitespace, including newlines.
Use a 'char' of a specific size char choice [1]
OR
char c[1];
c = getchar();
if(c[0] == 'y' || c[1] == 'y'){
// DO SOMETHING
}

c Exit if string is empty

I have the below code which is supposed to exit if the provided user input is empty i.e they press [ENTER] when asked for the input. However it doesnt do anything if [ENTER] is pressed.
printf("Enter the website URL:\n");
scanf("%s", str);
if(strlen(str) == 0) {
printf("Empty URL");
exit(2);
}
If the user just presses enter, the input will still contain a newline ('\n'). Your condition should be
if (!strcmp(str, "\n"))
I use a isempty function:
int isempty(const char *str)
{
for (; *str != '\0'; str++)
{
if (!isspace(*str))
{
return 0;
}
}
return 1;
}
Also, I would recommend using fgets over scanf, as scanf is unsafe and can lead to buffer overflows.
fgets(str, /* allocated size of str */, stdin);
%s with scanf() will discard any leading whitespace, of which it considers your Enter keypress. If you want to be able to accept an "empty" string, you'll need to accept your input in another way, perhaps using fgets():
printf("Enter the website URL:\n");
fgets(str, SIZE_OF_STR, stdin);
if(!strcmp(str,"\n")) {
printf("Empty URL");
exit(2);
}
Keep in mind the above code does not consider EOF, which would leave str unchanged.
shouldn't you check for '\n' - new line? Enter will represented as a new line character '\n'

validate the input

Part of the code is as follows but not work
printf("Enter a line of text (Enter to stop): ");
fflush(stdin);
fgets(input, 256, stdin);
if (input == '\0') {
exit(0);
}
.....
.....
i want if the user only press enter, the program will be terminated. how to do it?
thanks
Use if(*input == '\n') - if fgets reads a newline, it's stored in the buffer.

Resources