Undesired Output - Printing out Two Numbers - c

I'm fairly new to C programming, so I figured I'd try writing a simple program to
print two int numbers. I prompt the user for both numbers, and then just print both using printf
However, upon running the program, I get a result which is really bizarre.
For instance...
Enter first int: 5
Enter second int: 3
First int: 2130567168
Second int: 2686756
My code is below...
#include <stdio.h>
int main()
{
int x, y;
printf("Enter first number: ");
scanf("%i", x);
printf("Enter second number: ");
scanf("%i", y);
printf("%i\n%i%\n",x,y);
return 0;
}

This is because you forgot the & in the scanf statement. So change it to this:
scanf("%i", &y);
scanf("%i", &x);
//^ See here
Also you have one % too much in your printf statement. Because % is for format specifiers, so if you want to print the symbol % you have to write it 2 times:
printf("%i\n%i%\n",x,y);
//^ Is a format specifier so if you want to print the symbol, write it 2 times
Side note:
If you use the specifier %i in your scanf statement and you enter something like this: 035 the output would become 29, because it would be interpreted as octal number. So if you don't want that you can change the specifier to %d and 035 becomes 35

Change the code like this.
scanf("%i", &y);
scanf("%i", &x);
While storing the value to the variable you have to give the address of that variable. If you are using the arrays you don't need to give that. In printf statement , use the needed specifiers.
printf("%i\n%i\n",x,y);

You forgot the '&' in the scanf statement:
scanf("%i", &y);
scanf("%i", &x);
//^ this

Related

Anomalous scanf behaviour in C

I am trying to run the following code in C:
#include <stdio.h>
#include <stdint.h>
void main(){
int firstNum = 5;
int16_t secondNum;
printf("Please enter the first number: ");
scanf("%d", &firstNum);
printf("Please enter the second number: ");
scanf("%d", &secondNum);
printf("%d %d\n", firstNum, secondNum);
}
And the output I am getting is as follows:
Please enter the first number: 13
Please enter the second number: 4
0 4
--------------------------------
Process exited after 1.877 seconds with return value 4
Press any key to continue . . .
Why is that so?
My IDE is Dev-C++. Compiler is TDM-GCC 4.9.2 64-bit Release. Program name is TestBit.c (if that is relevant?).
Note: When I change the line int16_t secondNum; to int secondNum;, the program works as intended.
The proper specifier for int16_t secondNum is from <inttypes.h>
// scanf("%d", &secondNum);
scanf("%" SCNd16, &secondNum);
Better code would check the return value.
if (scanf("%" SCNd16, &secondNum) == 1) {
Success();
}
An int16_t is not the same thing as an int; so passing a pointer to one via scanf and pretending it is an int pointer can yield unexpected behaviour; thus your question.
Replace int16_t with int and your program works. For followup read the C Programming Language specification of types and what they mean.
Try changing to: scanf("%hd", &secondNum);
%d is a 4-byte data specifier, int16_t is actually only 2 bytes.
More references: https://learn.microsoft.com/en-us/cpp/c-runtime-library/format-specification-syntax-printf-and-wprintf-functions?view=vs-2019

Addition not working in c

I was trying c code to add but my program doesn't execute, codeblocks unfortunately closes. What is the error?
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,(a+b));
}
I want to put the result of addition directly in printf statement with float inputs but I am not getting it working.
I also tried putting the result in variable a but it didn't work either.
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
a=a+b;
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,a);
}
where am I going wrong?
The problem is in the following statement
printf("%30sAddition Of Numbers\n");
here, the format string supplied to the printf() conatins %30s (or, %s, in general) which is a format specifier (conversion specifier), and you did not supply any argument to it. It invokes undefined behavior.
To quote C11 standard, chapter §7.21.6.1
[...] If there are insufficient arguments for the format, the behavior is
undefined. [...]
You can also check the man page to find out more about the format specifiers.
EDIT:
As discussed in the below comments, if you want some spaces to appear before the output, change
printf("\t\tAddition Of Numbers\n");
That said,
void main() should be int main (void), at least, to conform to the standards.
You should always check the return value of scanf() to ensure the successful scanning.
The "%30sAddition Of Numbers\n" issue in your post has been addressed by two good answers (at the time of this post). But you asked a question in comments that may not have been answered completely:
works with %30s when i use all integer numbers and not float! how do i make it work with floats.
A generic answer to that question:
The format specifier you use in scanf(): "%f",&a could result in undesirable results if scanning in unexpected newlines, spaces or other white space. This can be addressed by modifying the format specifier string to suppress these characters. Here is a suggestion:
char* fmt = "%[^\n]%*c";//This generic format specifier, can be used for both integer
//and floating point inputs when used in conjuction
//with strtod() or strtol() (see below)
scanf(fmt, input);
Explanation of "%[^\n]%*c".
When a user is asked to enter a generic number, it might be a float or an integer. You can accommodate that by creating methods for both, and being specific about what kind of value you would like to process:
float get_float(void)
{
char input[80];
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter floating point number and hit return:\n");
scanf(fmt, input);
return strtod(input, dummy);
}
long get_int(void)
{
char input[80];
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}
Called like this:
int main(void)
{
long integer_var = get_int();
float float_var = get_float();
float sum = (float)integer_var + float_var;
return 0;
}
Try adding getch(); function at the bottom before closing curly brackets,
like this
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
a=a+b;
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,a);
getch();//it will hold your output screen so you can see the output
}
In this line
printf("%30sAddition Of Numbers\n");
you did not supply a string argument for the %s format. This causes undefined behaviour.
If you want the output spaced, you could try a small modification
printf("%30s\n", "Addition Of Numbers");
in this case you are supplying a string literal to satisfy the %s format.
Additionally you must always check the return value from scanf to see that it did convert the number of arguments it was supposed to. It's a basic newbie error not to, and the root cause of hundreds of SO questions.

Wrong output in calculating average program

For years, I don't do anything in C and now I can't do simple things, I was accustomed to cin and cout and now Java. I was trying to make a simple program to calculate the average X amount of exams notes. The output are "random numbers" and checking to interrupt the program occurs before entering a note. Why is that?
#include <stdio.h>
int main(void) {
int numeroDeNotas;
float nota = 0.0;
float notaAuxiliar = 0.0;
char continuar;
int media;
do{
printf("Enter the exam grade\n");
scanf("%f", &notaAuxiliar);
nota += (int) notaAuxiliar;
numeroDeNotas++;
printf("Do you want to continue? Enter n if you want to stop\n");
scanf("%c", &continuar);
}while(continuar != 'n');
printf("%d\n\n", nota);
printf("%d\n\n", numeroDeNotas);
media = nota/numeroDeNotas;
printf("Average grade: %d", media);
return 0;
}
nota is a float, but you are using %d format code to print it. %d expects an int; you need %f to print floating point numbers.
C's standard I/O formatting is definitely not typesafe. When you provide a format code, you have to make sure the corresponding argument has the right type. However, if you had compiled with the -Wall option (at least, with gcc or clang), the compiler would have warned you.
Also, scanf("%c", &continuar); reads a single character without skipping whitespace, which will be the character immediately following the number read by scanf("%f", &notaAuxiliar);. That character is most likely a newline. You need to skip whitespace before reading the y or n, so you could use:
scanf(" %c", &continuar);
numeroDeNotas was declared with a variable type - float. So you can't use %d later in your code when writing a printf statement.
numeroDeNotas
variable is declared but no where initialized. and you are incrementing in do while loop.
media = nota/numeroDeNotas;
printf("Average grade: %d", media);
and you are using garbage value to calculate media which is undefined output. initialize numeroDeNotas to zero.

Does GetInt() automatically create \n outputs here?

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.

having trouble with a "\n" and scanf

Here is the code
printf("\n");
printf("Enter a integer vaule:");
scanf("%d" , &num3);
printf("You entered: %015d", num3);
printf("Enter a float value:");
scanf("%f", &deci3);
printf("You entered: %15.2f", deci3);
printf("\n");
the output is
Enter a integer vaule:4.4
You entered: 000000000000004
Enter a float value:You entered: 0.40
The problem is this code is not stopping at
printf("Enter a float value:");
and this scanf
scanf("%f", &deci3);
seems to be getting its value from the previous scanf
The %d conversion stops wherever the integer stops, which is a decimal point. If you want to discard the input there, do so explicitly… getc in a loop, fgets, or such. This also allows you to validate the input. The program should probably complain about 4.4.
The scanf function works this way per the specification:
An input item shall be defined as the longest sequence of input bytes (up to any specified maximum field width, which may be measured in characters or bytes dependent on the conversion specifier) which is an initial subsequence of a matching sequence. [Emphasis added.]
In your example, the following C string represents the contents of stdin when the first scanf call requests input: "4.4\n".
For this initial call, your format string consists of a single specifier, %d, which represents an integer. That means that the function will read as many bytes as possible from stdin which satisfy the definition of an integer. In your example, that's just 4, leaving stdin to contain ".4\n" (if this is confusing for you, you might want to check out what an integer is).
The second call to scanf does not request any additional input from the user because stdin already contains ".4\n" as shown above. Using the format string %f attempts to read a floating-point number from the current value of stdin. The number it reads is .4 (per the specification, scanf disregards whitespace like \n in most cases).
To fully answer your question, the problem is not that you're misusing scanf, but rather that there's a mismatch between what you're inputting and how you're expecting scanf to behave.
If you want to guarantee that people can't mess up the input like that, I would recommend using strtol and strtod in conjunction with fgets instead.
This works, but it dont complains if you type 4.4 for the int
#include <stdio.h>
int main() {
char buffer[256];
int i;
float f;
printf("enter an integer : ");
fgets(buffer,256,stdin);
sscanf(buffer, "%d", &i);
printf("you entered : %d\n", i);
printf("enter a float : ");
fgets(buffer,256,stdin);
sscanf(buffer, "%f", &f);
printf("you entered : %f\n", f) ;
return 0;
}
use a fflush(stdin) function after the fist scanf(), this will flush the input buffer.

Resources