In my recently begun quest to learn C one of the first things I have made is a very basic "sum of 2 numbers program".
/* Basic addition prog */
#include <stdio.h>
int main(void) {
int v_1; /* first var */
int v_2; /* second var*/
int answer; /* Sum of 2 vars*/
printf("Simple addition calculator \n");
printf("enter first number: ");
scanf("%d", &v_1);
printf("enter second number: ");
scanf("%d", &v_2);
answer = v_1 + v_2;
printf("%d\n", answer);
}
When I run this and enter 2 numbers everything runs fine and I will get the correct answer.
The output will look like:
enter first number: 1
enter second number: 1
=2
I decided I'd try and break it by using letters instead of numbers expecting at first that I'd input 2 letters and it'd either convert them into numeric values or would error out and crash.
However this isn't what happens instead I get the following:
enter first number: a
enter second number: = 32765
My question isn't so much "how do I fix this" as it is "what is actually happening here?
EDIT
Again this question is more about trying to understand what is happening than trying to fix a problem. I'm not looking for "how can this be avoided?" I'm looking for "what causes it and why?"
Tl;Dr
I really can simplify what I want to know down to 2 questions.
Why am I getting unique junk data for each letter of the alphabet that I enter?
i.e 32764 for every time I enter a and 32767 every-time I enter b ?
Why does the second variable input get skipped ?
Check the result of scanf("%d", &v_1);. If it is not 1, v_1 is not updated.
Why does the second variable input get skipped ?
Entering non-numeric input for scanf("%d", &v_1); will neither consume that input nor change v_1.
That is also why scanf("%d", &v_2); did not wait for input, it tried to use the same input and also failed.
Why am I getting unique junk data for each letter of the alphabet that I enter? i.e 32764 for every time I enter a and 32767 every-time I enter b ?
Code is just getting the uninitialized values of v_1, v_2. An optimizing compiler may not even "create" v_1 until the scanf("%d", &v_1); and so the uninitialized v_1 may be dependent on the text entered. Since this is undefined behavior, the result may differ tomorrow or on another machine.
Try the same thing with initialized values.
int v_1 = 0; /* first var */
int v_2 = 0;
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 am getting comfortable with the foundations of C:-
There are two iterations of scanf() in this program. The first is fully functional.
The second appearance does nothing and instead quits the program and returns to the standard command prompt line.
Also, my second for loop only prints the first 4 numbers instead of 5.
Here is the code :
int main() {
int i;
int iNum[4]
int iMenu = 0;
printf("\n\n\tPlease enter five numbers: ");
for (i = 0; i < 4; i++) {
scanf("%d ", &iNum[i]);
}
printf("\n\tThank you. Here are your numbers: \n\t");
for (i = 0; i < 4; i++) {
printf("%d", iNum[i]);
}
printf("\n\tMenu:");
printf("\n1\tSort your numbers ascending.");
printf("\n2\tSort your numbers descending.");
printf("\n3\tQuit program");
printf("\n\nWhat would you like to do?\n\tEnter your option here: ");
scanf(" %d", &iMenu);
switch (iMenu) {
case 1:
printf("\nCase1testPrint");
sortAsc();
break;
case 2:
printf("\nCase2testPrint");
sortDesc();
break;
. . .//rest of code }
As soon as the program reaches the second scanf(), the program ends and returns to command prompt.
This is baffling, and I have tried many variations on what could be wrong. Please provide what you may.
Here is what it looks like if I run the program. Notice my entry "1" appears in the command line instead of the program:
C:\Users\Cortland\Documents\C projects>gcc arraysort.c
C:\Users\Cortland\Documents\C projects>a
Please enter five numbers: 3
6
5
4
5
Thank you. Here are your numbers:
3 6 5 4
Menu:
1 Sort your numbers ascending.
2 Sort your numbers descending.
3 Quit program
What would you like to do?
Enter your option here:
C:\Users\Cortland\Documents\C projects>1
Your for loop reads four numbers, not five.
You enter five numbers. The first four are read in the for loop. The fifth is read by
scanf(" %d", &iMenu);
So you've entered 3 6 5 4 as the four numbers, and then 5 as the choice of what to do. You haven't shown us the entire switch statement, but my guess is that it doesn't handle the value 5, and that it falls through and your program terminates.
(Also, you should always check the value returned by scanf(), and take some action if it indicates that the input operation failed.)
There are a couple of errors.
First off, the second line of your main() function contains a syntax error - there should be a semicolon at the end. This should stop your program from even compiling.
Second, even though you say you want the user to enter 5 numbers, your array and loops all use the number 4. The reason your program still allows you to enter five numbers, however, is because of how you've written the formatting string in your calls to scanf(). Instead of:
scanf("%d ", &iNum[i]);
use
scanf("%d", &iNum[i]);
Notice the lack of a space at the end of the formatting string? That's where your problems come in. Even though you are allowed to enter five numbers, the program only stores and checks four of them. The last number is stuck in the input stream - until, that is, your next call to scanf(). This fetches your last number, which is put through the switch/case statement (failing all cases, since you didn't input "1", "2" or "3"), and the program reaches the end of main() and exits. The "1" in the command line comes from trying to input something when the program has already ended.
Summarized:
1: Add the missing semicolon
2: Change the number used in the declaration of iNum and in the for loops from 4 to 5
3: Edit your scanf() calls, removing whitespace from the formatting strings.
This fixed the problem on my end.
This question already has answers here:
Yes/No loop in C
(3 answers)
Closed 8 years ago.
I am trying to execute a small program using do-while.
#include<stdio.h>
#include<conio.h>
void main()
{
char another;
int num;
do
{
printf("Enter a number");
scanf("%d",&num);
printf("Square of %d id %d",num,num*num);
printf("Want to another another number y/n");
scanf("%c",&another);
}while(another=='y');
}
Now when I try to execute the program, it runs fine. I input a number and it displays its square. And then I see Want to enter another number y/n. But as soon as I press any key (y or n), the program exits itself before I can press enter to provide the input. I tried it many times but no success.
But the program runs fine if I ask the user to input either 1 or 2(in place of y/n). In that case it takes an integer input and can check the while block. If another == 1, the program runs again.
My problem is that why can't I check for a character in the while condition.
The reason it doesn't work is that after scanf gets num, the new line is still in the buffer, so it will be processed by the next scanf with %c format specifier. A direct way of fixing it is to use:
scanf(" %c", &another);
// ^space
Note that your original scanf("%c:,&another); won't compile, but I assume that's a typo. And always use int main, or it's undefined behavior.
I want to write a program where it prompts people to enter a set of integers separated by a space. The user should be able to enter any amount of integer. It will find the two smallest integer in the set and print it out. Printing the smallest number and then printing the second smallest. My question is how do I get the value of min1 to be the first integer they enter, other than a static one? When I did a test run all it printed was a space, why is that? Here is what I have so far:
Update:
I'm now trying this approach, but it just freeze after I enter an input such as 76 5 74 2.
#include <stdio.h>
int min1, min2;
int input;
int main(){
printf("Please enter some integer: ");
scanf("%d", &min1);
while(scanf("%d", &input) != 0){
min1=input;
}
printf("%d", min1);
return 0;
}
You should add \n in the end of the first printf, so it will not buffered.
Also, be care that you work with digits - not integers.
and for your question - just write min1=getchar();.
EDIT: some code that may do what that you want:
printf("Enter numbers. (other chars to end)\n");
int min,input;
scanf("%d",&min);
while (scanf("%d",&input))
if (input<min)
min=input;
printf("min: %d\n",min);
Maybe you need scanf("%d", &number); to read integers.
For your question, just call scanf to read the first number, or set up a flag to indicate if it's the first input.
Why did you got a space printed? Because %c prints characters not numbers, try %d.
But even after that you won't get the answer you are looking for. getchar() gets a character (go figure...) from the user input, and you are storing that character into a numeric value, for single digit numbers it would magically work since even as characters '9' > '8' > '7' > ... > '0', but you'll get the ascii value of the smallest number printed at the end.
You need two things:
Some way for the user to tell your program they are done entering numbers, so some kind of conditional statement
Some way to compare the numbers they have entered so another conditional statement comparing numbers
In sudocode, maybe something like:
while (user still wants to give numbers):
number = get user input
if number does not equal exit_case:
if number < current minimum number:
current minimum number = number
else:
break out of the while loop
print current minimum number
{
int a,b=1,min;
printf("Enter Number\n");
scanf("%d",&min);
while(b<10)
{
scanf("%d",&a);
if(min>a)
{
min=a;
}
b++;
}
printf("Smallest Num ::%d",min);
}
I'm trying to write a simple program where it ask user to enter a bunch of positive integers, and calculate the average of all the number entered. Program will terminate when user enter a non positive number like 0 or -1.
Here is my code. For some reason I get an error right when I try to enter the first input, can someone help?
#include <stdio.h>
int main()
{
int input=0, sum=0,average=0,i=0;
printf("Please enter positive numbers, enter 0 or -1 to end:\n");
scanf("%d",input);
while (input>0)
{
sum+=input;
i++;
scanf("%d",input);
}
average=sum/i;
printf("The average is %d",average);
}
You need to pass the address of the variable to scanf.Try this:
scanf("%d", &input);
^
Also see the C FAQ: Why doesn't the call scanf("%d", i) work?