Suppose I have code that asks the user to give 2 integers, and when the user give the integers, the program prints the sum.
int main(void)
{
printf("Please give me an int: ");
int x = GetInt();
printf("Please give me an int: ");
int y = GetInt();
printf("%d\n", x + y);
}
When I run the program, all three printf's appear on separate lines.
My question: What I don't understand is why the first two printf's do not require \n in order to move to a new line, yet the third printf does require \n.
The \n for the first two is provided by the user when they hit enter after inputting their number.
Related
I've written a small program to practice getting user input using getchar() and outputting it using putchar() in C.
What I want my program to do:
I want the program to ask the user to enter a char, store it in a char variable, and print it out. And then I want it to ask the user to enter another char, store it in another char variable, and print it out.
The following is my code:
#include <stdio.h>
int main()
{
printf("Please enter a char: ");
char myChar = getchar();
printf("The char entered is: ");
putchar(myChar);
printf("\n");
printf("Please enter another char: ");
char myChar2 = getchar();
printf("The char entered is: ");
putchar(myChar2);
printf("\n");
return 0;
}
When I run this program in my Terminal, the following is what I see, which is not how I expect it to behave.
cnewbie#cnewbies-MacBook-Pro c % ./a.out
Please enter a char: k
The char entered is: k
Please enter another char: The char entered is:
cnewbie#cnewbies-MacBook-Pro c %
When I run the program, it outputs "Please enter a char: " and waits for me to enter a char. I type k and hit return. Then it outputs not only "The car entered is: k" but also the other lines shown above all at once.
Question: Why doesn't my program wait for me to input another char?
I'm a beginner in C and I have no clue why this is behaving this way. Please help!!
getchar also reads white space characters including the new line character '\n' that is placed in the input buffer due to pressing the Enter key.
Instead use a call of scanf the following way
char myChar;
scanf( " %c", &myChar );
^^^^
Pay attention to the leading space in the format string. It allows to skip white space characters.
This question already has answers here:
Why is scanf() causing infinite loop in this code?
(16 answers)
Closed 4 years ago.
I'm trying to write a C program that computes X^Y (X to the Y power) without using the 'pow' function. The program works fine when I enter numbers, but I'm having an issue with the code not stopping when the user enters a character that isn't a number. It runs through the program once more after giving the message "The character you have entered is not a number.Please try again.The character you have entered is not a number.Please try again. The value is 1." Can someone help? I'm going insane trying to figure this out.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, y, i,n=1,val;
printf("Please enter a number: \n");
scanf("%d", &x);
if (x!=1)
printf("The character you have entered is not a number.Please try again.");
else
printf("What power is the number raised to?\n");
scanf("%d", &y);
if (y!=1)
printf("The character you have entered is not a number.Please try again.");
else
for(i=1;i<=y;i++)
{
val=x;
n=n*val;
}
printf("The value is %d.\n", n);
return 0;
}
When your program detects invalid input, it prints a message, but otherwise just continues on ahead as if a valid input had been read. Instead, it needs to do one of these things:
abort when invalid input is detected, or
consume and ignore the invalid input, AND
loop back to provide a chance to enter new input, or
use a default value.
Its message suggests that the program will provide for entering new input, but in fact it does not follow through. Moreover, if it is the input for the first prompt that is invalid, then that input is still waiting to be read when the program prints the second prompt, where it is still invalid, and the program blithely continues on a second time, ultimately printing the initial value of n, 1, without having calculated anything.
You need to check how many items scanf successfully read:
int numItemsRead = 0;
printf("What power is the number raised to?\n");
numItemsRead = scanf("%d", &y);
if (numItemsRead!=1)
printf("The character you have entered is not a number.Please try again.");
} else {
'''
}
int main()
{
int x, y, i,n=1,val;
printf("Please enter a number: \n");
scanf("%d", &x);
if (x!=1)
printf("The character you have entered is not a number.Please try again.");
return 0;
else
printf("What power is the number raised to?\n");
scanf("%d", &y);
Maybe if u do like that even if u entered a invalid character program will be end.
Okay so I'm trying to do a basic program in VS. Enter a number then it gets printed out. 1 is always printed.
int main(){
printf("Enter an integer: ");
int n = scanf_s("%d", &n);
printf("%d", n);
}
You are assigning the returned value from scanf_s() to the variable n, that means that the program will print 1 in case a successful read happened.
What you should do is
int numberOfItemsMatched;
int readValue;
numberOfItemsMatched = scanf_s("%d", &readValue);
if (numberOfItemsMatched == 1)
printf("%d\n", readValue);
I hope the variable names are self explanatory, and it's always a good idea to use this kind of names.
return type of scanf is number of items read. so if scanf is succesful in reading an item, it returns one which is assigned to n here. hence the output is 1. So separate declaration of n and scanf.
#include<stdio.h>
void main(){
int num1,num2;
printf("\n Enter number 1 \t "); // Ask for input one. >>>>>>>> line 1.
scanf("%d ",&num1);
printf("\n Entered number is %d \n",num1);
printf("\n Enter number 2 \t "); // Ask for input Two. >>>>>>>>> line 2.
scanf("%d ",&num2);
printf("\n Entered number is %d \n",num2);
return;
}
I wish to know REASON.Please do provide it.
The code above accepts two inputs,first input is asked(By executing line 1) then user enter one number then terminal should ask to enter second input but instead it is taking other number(before executing line2 ) and then asking to enter second input(i.e after executing line 2).
In the End is is displaying the two input that are taken before executing line two but after executing line 1.
I am confused.I am interested to know reason.
I am using GCC 4.8.2 on ubuntu 14.04 64 bit machine.
Remove spaces between the scanf of access specifier.
scanf("%d ",&num1);
to
scanf("%d",&num1);
Because the scanf get the another value due to that spaces.
And kept in the buffer. After the memory has got it get assigned.
It is for all scanf function.
if I input like
Enter Number1 1
2
Entered number is 1
Enter number2 3
Entered number is 2.
It is better to use int main() and in the end write return 0;
use fflush(stdout); to flush your buffer.
After editing here is the final code
#include<stdio.h>
int main(){
int num1,num2;
printf("\n Enter number 1 \t "); // Ask for input one. >>>>>>>> line 1.
scanf("%d ",&num1);
printf("\n Entered number is %d \n",num1);
printf("\n Enter number 2 \t "); // Ask for input Two. >>>>>>>>> line 2.
fflush(stdout);
scanf("%d ",&num2);
printf("\n Entered number is %d \n",num2);
return 0;
}
Here is the Demo.
You need to put
fflush(stdout);
before the scanf
This will flush your buffer
(also a good idea to check the return value of scanf)
You have given a space in scanf for %d. If you remove that space after %d the program will run
Let's take this apart slowly
#include <stdio.h>
// void main(){
int main(void) {
int num1, num2;
printf("\n Enter number 1 \t ");
scanf("%d ",&num1);
printf("\n Entered number is %d \n",num1);
...
Use a proper function signature for main() - but that is not the main issue.
Code prints "\n Enter number 1 \t "
"%d" directs scanf() to scan for text convertible to an int in 3 steps:
A: Scan for optional leading white-space like '\n', '\t', ' '. Throw them away.
B: Scan for text representing an integer like "+1234567890". If any digits found, save the converted result to the address &num1.
C: Scanning continues in step B until a char that does not belong to the int is found. That char is "un-read" and returned to stdin.
(This is where you get in trouble as suggested by #Chandru) " " directs scanf() to scan for any number (0 or more) white spaces including '\n', '\t', ' ' and others. Then they are thrown away - not saved.
B: Scanning continues!! until a non-white-space is found. That char is "un-read" and returned to stdin.
Lastly scanf() return the value of 1 as that is how many field specifiers were converted. Code sadly did not check this value.
Recall stdin is usually line buffered, which means input is not available to user IO until Enter is hit.
User enters 1 2 3 Enter and scanf() scans the "123" and saves 123 to &num1. Then it scans "\n" as that is a white-space in step 4. and it continues waiting for more white-space.
User enters 4 5 6 Enter and the first scanf() which is not yet done, scans '4', sees it is not a white space and puts '4' back in stdin. scanf() finally returns after 2 lines are entered. At this point "456\n" are waiting in stdio for subsequent scanf().
The second scanf() then perpetuates the issue.
Recommend use fgets() only for all user input, at least until your are very skilled in C.
printf("\n Enter number 1 \t ");
char buf[100];
fgets(buf, sizeof buf, stdin);
if (sscanf(buf, "%d", &num1) != 1) Handle_BadInput();
else printf("\n Entered number is %d \n",num1);
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);
}