When I enter a string in the code below, the program doesn't move on. It just allows me to keep typing and pressing enter with no effect. Why does this happen and how can I fix it.
#include <stdio.h>
main() {
char str[20];
int aaa = 0;
int exit;
printf("Enter anything: ");
scanf("%s", str);
while(aaa == 0) {
if(str[3] == 'a') {
aaa++; }
else {
scanf("%d", &exit);
if(exit == 3) {
aaa++; } } }
printf("%s\n", str);
}
Log:
Enter anything: 2/3/4444
Now
it
just
lets
me
keep
on
typing
Edit: I solved it and I’m a bit embarrassed at how simple it was. I know people have been trying to explain this to me but in my own words this is what was happening: as the condition to enter the while loop was being met the program would enter the while loop. However, unless the input entered for the scanf satisfied one of the conditions in the loop, the program had no way of leaving the loop and therefore, it would get stuck. Basically I was simply missing an else statement which solved this problem.
After a string whose fourth character is not an a, your program reads an integer. It will never attempt to read anything but an integer after that first read. So you must not enter anything but an integer after the first string.
If you want your program to handle a non-integer after the string, you need to add code to do that. You currently have none.
Related
fairly new programmer here just trying to understand if there is a better way to do this and hoping to get some feedback.
TL;DR: Is there a better way to clear stdin when looking for a specific input?
For some background, I've been learning C for the past 3 weeks and scanf() has been our "go to" function for user input. After looking around for answers to this question, I'm beginning to learn that scanf() is not always preferred.
In this part of the assignment that I'm working on, I created this while loop that is supposed to run while the user input is a nonzero, positive integer. It took a while, but to get to this point I now understand that if a string is inputted instead of an integer when scanf("%d", &variable); is assigned while using leads to an infinite loop as stdin does not get cleared.
I tried to solve this problem by checking to see the return of the scanf() functions, and running the loop while the return is equal or less than 0 (which would mean that the scanf() function broke and did not return anything since it saw a char instead of an int).
The thing is, the code seems to work great until we encounter one scenario, which is where we have characters followed by an integer.
For example:
Input = 1
program runs with no issues
Input = string
program runs loop, asks for new valid input
Input = string string
program runs loop, asks for new valid input
Input = 123string
program proceeds, but then next loop with an int scanf() is infinite. 123 is stored as an int to variable.
My current understanding of the issue is that scanf() reads the integers until we get to the characters and then "string\n" gets stored to stdin, creating an infinite loop in the next part. To solve the issue, I added a fflush(stdin); before the next integer scanf() loop which seems to work.
So my question is: Would somebody be willing to show me some other ways to do this other than adding a fflush(stdin); line before every int scanf() loop? I'm sure there are better ways but I don't rightly know who to ask and the internet seemed like a good resource. Thank you.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int squareLen = 0;
int numColors = 0;
int infiniteLoopStop;
// Asks for user input of desired Square Length
printf("Please enter the finished side length (in inches) of one square.\n> ");
while (squareLen < 1) {
infiniteLoopStop = scanf("%d", &squareLen);
if (infiniteLoopStop <= 0 || squareLen < 1) {
printf("\nInvalid input. Enter a nonzero, positive integer.\n> ");
fflush(stdin);
}
}
// Temporary solution to problem
fflush(stdin);
// Asks for int input of colors and loops while number of colors is not 2 or 3
printf("How many colors are you using? Enter 2 or 3.\n> ");
while (numColors < 2 || numColors > 3) {
infiniteLoopStop = scanf("%d", &numColors);
if (infiniteLoopStop <= 0 || numColors < 2 || numColors > 3) {
printf("Invalid, please enter 2 or 3.\n> ");
fflush(stdin);
}
}
printf("\n");
return 0;
}
I want for my program to just ask again if the user entered a letter or just pressed enter.
I know that if the input is not a number scanf() will return 0, so i have been doing this:
int variable;
printf("Please write an integer and then press enter: \n");
if (scanf("%i",&variable)!= 1) { /* ERROR CODE */; return 1;}
return 0;
But i dont want for my program just to stop if the input is not correct. So i tried this:
int variable;
do
{
printf("Please write an integer and then press enter: \n");
} while (scanf("%i",&variable) != 1);
But the program will just start printing "Please write an integer and then press enter:" without stoping. Is there a way of doing this?
edit: Forgot the &
edit2: Thanks to everybody.
edit3: I have been looking into the functions. Will this code be correct?
char variable[10]; int var;
do
{
printf("Please write an integer: ");
fgets(variable,sizeof(variable),stdint);
} while( sscanf(variable,"%i",&var) != 1 );
I have tried it and it works but i post it here because i know im probably missing something.
int variable;
do {
printf("Please write an integer and then press enter: \n");
} while (scanf("%i", &variable) != 1 && scanf("%*[^\n]") == 0);
The second scanf discards characters till the '\n' character. The '\n' character remains, though it will be skipped by the first scanf on the next iteration of the loop.
The code has some defects but it will work in most cases. One defect is that, if scanf returns EOF without reading a character then the loop will exit but the value of variable will be indeterminate, which can cause undefined behaviour when used. This one is not difficult to cure. Another one is that, the behaviour is undefined if the user enter a number outside of range for int. So a way better approach, is to use fgets and strtol library functions.
I am new to C programming. I have been writing this code to add numbers and I just need help with this one thing. When I type the letter 'q', the program should quit and give me the sum. How am I supposed to do that? It is currently the number 0 to close the program.
#include <stdio.h>
int main()
{
printf("Sum Calculator\n");
printf("==============\n");
printf("Enter the numbers you would like to calculate the sum of.\n");
printf("When done, type '0' to output the results and quit.\n");
float sum,num;
do
{
printf("Enter a number:");
scanf("%f",&num);
sum+=num;
}
while (num!=0);
printf("The sum of the numbers is %.6f\n",sum);
return 0;
}
One approach would be to change your scanf line to:
if ( 1 != scanf("%f",&num) )
break;
This will exit the loop if they enter anything which is not recognizable as a number.
Whether or not you take this approach, it is still a good idea to check the return value of scanf and take appropriate action if failed. As you have it now, if they enter some text instead of a number then your program goes into an infinite loop since the scanf continually fails without consuming input.
It's actually not as straightforward as you'd think it would be. One approach is to check the value returned by scanf, which returns the number of arguments correctly read, and if the number wasn't successfully read, try another scanf to look for the quit character:
bool quit = false;
do
{
printf("Enter a number:");
int numArgsRead = scanf("%f",&num);
if(numArgsRead == 1)
{
sum+=num;
}
else // scan for number failed
{
char c;
scanf("%c",&c);
if(c == 'q') quit = true;
}
}
while (!quit);
If you want your program to ignore other inputs (like another letter wouldn't quit) it gets more complicated.
The first solution would be to read the input as a character string, compare it to your character and then convert it to a number later. However, it has many issues such as buffer overflows and the like. So I'm not recommending it.
There is however a better solution for this:
char quit;
do
{
printf("Enter a number:");
quit=getchar();
ungetc(quit, stdin);
if(scanf("%f", &num))
sum+=num;
}
while (quit!='q')
ungetc pushes back the character on the input so it allows you to "peek" at the console input and check for a specific value.
You can replace it with a different character but in this case it is probably the easiest solution that fits exactly what you asked. It won't try to add numbers when the input is incorrect and will quit only with q.
#Shura
scan the user input as a string.
check string[0] for the exit condition. q in your case
If exit condition is met, break
If exit condition is not met, use atof() to convert the string to double
atof() reference http://www.cplusplus.com/reference/cstdlib/atof/
I am currently trying to get a while loop working, but it's not going the way I want it too. What I want to do is loop until a specific input is put in. Something must be wrong with my syntax, but I can't figure out what.
#include <stdio.h>
int main()
{
float input = 0;
scanf("%f", &input);
while(input!=0)
{
printf("hello\n");
scanf("%f", &input);
}
return 0;
}
For some reason, it doesn't break out of the while loop when it is zero. I want the while loop to stop working after someone enters 0, but when someone enters 0 it will create an infinite printing of "hello" instead..As you may have guessed, input becomes 0 whenever the user inputs anything besides a float, so if I enter a letter, I am expecting the while loop to stop, but it doesn't ;\
Edit:
Thank you guys for help! I learned and figured out why my logic was wrong (due to lack of understanding how to test the value of scanf)!! Cheers.
input does not become zero if the user enters a non-float. scanf won't change the value, and it won't consume any characters. So, if the user enters a non-float, scanf will keep reading the same characters over and over again.
You can test the scanf return value to see if it successfully read anything. scanf returns the number of fields that were successfully read, so a return value of 0 means that it failed to parse anything:
while(scanf("%f", &input) == 1) {
printf("You entered %f\n", input);
}
Write the loop like
while(input!=0)
{
printf("hello\n");
input = 0.0;
scanf("%f", &input);
}
How can I make a loop that can take user input every time it loops?
#include <stdio.h>
#define WORD "jumble"
#define JUMBLED "mleujb"
int main()
{
char string[6];
int i = 0;
printf("The jumbled word is ");
printf(JUMBLED);
printf("\nCan you guess the original: ");
while(i == 0)
{
scanf("%d", string);
if (string == "exit")
{
return;
}
if(string == WORD)
{
i++;
printf("Kudos! You've guessed the word!");
}
else
{
printf("English please, good sir. Guess again.\n");
}
}
}
What I had hoped for was that every time the program went through the loop, it would want a new input with the scanf function. However, that apparently does not work that way. Instead, the program takes the value of the first scanf and uses it over and over again. If it is the wrong word, it will have an infinite loop.
This program has more than a few bugs in it: for instance, it does not actually compare the input to the actual word yet. As that does not pertain to the question, it is not my immediate concern.
you are using scanf() wrongly instead of scanf("%d",string) use scanf("%s",string) as %d is used for decimal input and %s is used for string input
Pseudo code for helping you precisely is not great
Also can you define a bit better your question ? you don't really say what is going wrong
but here is my guess
your test is i ==0 which means as soon as your user inputs the right word your exiting your loop...
I would guess your looking for something like
exit_condition = 0;
while (exit_condition == 0)
{
read keyboard entry
if(condition to exit loop)
{
exit_condition = 1;
printf("correct")
}
else
{
printf("try again")
}
}
Concerning the tests I think you need to read up bit on input and tests
try this
http://www.arachnoid.com/cpptutor/student1.html
scanf is incorrect for getting input string. It should be scanf("%s", string) as pointed out by others
String comparison cannot be done by using == in 'C'. It will only compare the address of two strings which will fail. Use 'strncmp' function instead.