Learning C, looping error [duplicate] - c

This question already has answers here:
i want to getchar twice but i cant
(2 answers)
Closed 7 years ago.
I have been tasked to create a simple lower to upper case program. However, while testing if my input prints correctly, I have noticed that every time I enter a character, it always loops again even when its not supposed to.
#include <stdio.h>
int main() {
char input;
//enter a character
//set the given input char to variable
printf("Enter a character in lower case: \n");
input = getchar();
//Sentinel value is Q
while (input != 'Q'){
printf("you entered %c.\n",input);
printf("\n");
printf("Enter a character in lower case: \n");
input = getchar(); //gets input from inside the loop
}
printf("Goodbye \n");
return 0;
}
test output (I input the character 'g' and pressed enter once):
Enter a character in lower case:
g
you entered g.
Enter a character in lower case:
you entered
.
I'm not seeing the problem.

The problem here is caused by the newline character entred into the stdin by pressing the ENTER key. Before proceeding for the next input, you need to clear the input buffer , like adding
while (getchar() != '\n');
before asking for the next input.
That said, getchar() returns an int. A char may not be enough to hold the return value always, Change
char input;
to
int input = 0;

Related

C language, how can I check if a given input is a character or a positive int [duplicate]

This question already has answers here:
How to scanf only integer?
(9 answers)
Closed 4 years ago.
I want to know how to keep taking inputs from keyboard with this condition: If the given input is a positive number, it keeps going with the code If the given input is a negative number or a letter, it must print "insert a positive number" and then ask again for another input until it has the correct one. About negative and positive inputs the code i wrote works great, but it bugs out when I put a letter. The check I tried is the following
chk=isalpha(n);
while(!chk || n<0)
{
printf("Inserire un intero positivo \n");
scanf("%d", &n);
chk=isalpha(n);
}
printf("%d\n%d\n", t1, t2);
In this case if I put a negative number it works correctly, but if I type a letter the printf loops. I also tried while(isalpha(n) || n<0) And a bunch of other pieces of code I'll skip for you. Please help me figure this out
You can check return value of scanf in case of char it returns 0 along with that you need to clear the buffer to stop scanf consuming the same character.
Example:
int ret = 0;
do
{
char c;
while ((c = getchar()) != '\n' && c != EOF) { } /* to clear the bad characters*/
printf("Inserire un intero positivo \n");
ret = scanf("%d", &n);
}while(!ret || n<0);

Why didn't getchar take input? [duplicate]

This question already has answers here:
i want to getchar twice but i cant
(2 answers)
Closed 7 years ago.
I have been tasked to create a simple lower to upper case program. However, while testing if my input prints correctly, I have noticed that every time I enter a character, it always loops again even when its not supposed to.
#include <stdio.h>
int main() {
char input;
//enter a character
//set the given input char to variable
printf("Enter a character in lower case: \n");
input = getchar();
//Sentinel value is Q
while (input != 'Q'){
printf("you entered %c.\n",input);
printf("\n");
printf("Enter a character in lower case: \n");
input = getchar(); //gets input from inside the loop
}
printf("Goodbye \n");
return 0;
}
test output (I input the character 'g' and pressed enter once):
Enter a character in lower case:
g
you entered g.
Enter a character in lower case:
you entered
.
I'm not seeing the problem.
The problem here is caused by the newline character entred into the stdin by pressing the ENTER key. Before proceeding for the next input, you need to clear the input buffer , like adding
while (getchar() != '\n');
before asking for the next input.
That said, getchar() returns an int. A char may not be enough to hold the return value always, Change
char input;
to
int input = 0;

why %s does not print the string after it encounters a space character? [duplicate]

This question already has answers here:
How do you allow spaces to be entered using scanf?
(11 answers)
Closed 6 years ago.
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output:
Enter name: Dennis Ritchie
Your name is Dennis.
So far I haven't found any specific valid reason for this question. Can anyone help me out?
scanf only read till it gets to space that is why it is not storing after the first space , so your printf function is not faulty , it is the scanf that is not storing the complete string , stopping on encountering first space.
One should never use gets() , unless they completely know what they are doing , because it does not have buffer overflow protection , it continue to read after the buffer ends until it finds a new line or encounter a EOF. You can read more about that here.Please Check This Why is the gets function so dangerous that it should not be used?
You should instead use fgets().
#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
fgets(name,20,stdin);
printf("Your name is %s.", name);
return 0;
}
Remember fgets() also reads newline character(the one you get when you press enter) so you should manually remove that.
Also I highly Recommend this answer for using fgets() to its full potential and avoiding common pitfalls.
This answer tells about using scanf to read string.What it says is the following:
int main(){
char string[100], c;
int i;
printf("Enter the string: ");
scanf("%s", string);
i = strlen(string); // length of user input till first space
do{
scanf("%c", &c);
string[i++] = c; // reading characters after first space (including it)
}while (c != '\n'); // until user hits Enter
string[i - 1] = 0; // string terminating
return 0;
}
How this works? When user inputs characters from standard input, they will be stored in string variable until first blank space. After that, rest of entry will remain in input stream, and wait for next scanf. Next, we have a for loop that takes char by char from input stream (till \n) and appends them to end of string variable, thus forming a complete string same as user input from keyboard.

C Newbie. My program has two parts to it but the whole thing pops up at the same time [duplicate]

This question already has answers here:
Program doesn't wait for user input with scanf("%c",&yn);
(5 answers)
Closed 7 years ago.
I managed to make this simple two part program which consists of simple print and scan functions. The first part is an addition operation and the second part asks the user for a letter and then it repeats it to the user. The first part goes well but when it finishes and is supposed to start the second part it shows the whole thing before I can input a letter.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int num1, num2 = 522;/*input a number*/ /*add 522*/
int sum; /*sum of num1 and num2*/
char let; /*Letter to put in*/
printf("Hello, my name is John Doe.\n"); /*Print "Hello my name is*/
printf("Please type a number= "); /*Ask user for num1*/
scanf("%d", &num1); /*Scan for num1*/
sum = num1 + 522; /*Add 522 to num1*/
printf("The sum of %d and %d is %d\n", num1, num2, sum);/*print num1 and sum*/
printf("Please type a letter= \n"); /*Ask user for letter*/
scanf("%c", &let); /*Scan for letter*/
printf("You typed %c\n", let); /*Show the letter input*/
return 0;
}
Change
scanf("%c", &let);
to
scanf(" %c", &let);
There is a newline character after a number is entered so that is picked by %c you need to ignore it. Note the space before %c
A better approach is flushing the input buffer after every scanf()/getchar() call.
while ((ch = getchar()) != '\n' && ch != EOF);
but don't use fflush(stdin) because if the file stream is for input use, as stdin is, the behaviour is undefined, therefore it is not acceptable to use fflush() for clearing keyboard input.
As usual, there are some exceptions, check your compiler's documentation to see if it has a (non-portable) method for flushing input.
you can use getchar() function as well to clean the new line character but first method is recommended.

How do I fix scanf? (FailSafes) [duplicate]

This question already has answers here:
Why does scanf appear to skip input?
(7 answers)
Closed 8 years ago.
Here i have a simplified piece of code that asks and displays a number on a loop, it works fine for all numbers i type in, But if i input a letter or a special character (!"£$%^&*-_=+ etc ) it goes mental and skips the input.
#include<stdio.h>
int number;
int main()
{
do
{
system("cls");
printf("Enter a number");
scanf("%d",&number);
}
while(1==1);
}
My question is, what can i do to stop this from happening?, is there some code that filters out this nonsense or is scanf pretty much worthless?
//Edit: This is somehow been marked as a duplicate, heh.
From here:
if the input doesn't conform to the expected format scanf() can be
impossible to recover sensibly [..] A "better" alternative here is to
use an input function like fgets() or fgetc() to read chunks of input,
then scan it with sscanf() or parse it with string handling functions
like strchr() and strtol().
scanf with %d will fail to scan an integer and returns 0 when a character was entered. So just check if it doesn't return 1. If it doesn't , a character was entered (if it returned 0) or else, an integer was entered. Note that if EOF was encountered, scanf will return -1.
if(scanf("%d", &number) != 1)//character entered
{
printf("Invalid input\n");
scanf("%*s");//clear the invalid character(s) from stdin
}
else
{
//a number was entered
}
The reason that scanf becomes "mental" and the program prints Enter a number many times when you enter a character is that when the scanf fails to scan an integer from the standard input stream(stdin), it returns 0 and the execution continues. When scanf is called the next time, it sees the characters which you had entered the last time and again fails and this process continues. To prevent it, just clear the stdin like I've done in the code above.
Another popular way of clearing the stdin is using:
int c;
while((c = getchar()) != '\n' && c != EOF);

Resources