after printf program ends itself without doing the rest of code ? C - c

after printf line program ends itself but i didnt get it why.
#include<stdio.h>
int main ()
{
int Sum,multiply,divide,difference,num1,num2;
char i;
scanf("%d", &s1);
scanf("%d", &s2);
printf("Type initial of your operation : ");
scanf("%c", &i);
return 0 ;
}

There is no way you could compile that, since s1 and s2 are undefined variables.
Thus, any information about what happened when you ran it is moot, since there is no way you could run it.
You meant:
if(scanf("%d %d", &num1, &num2) == 2)
{
printf("Operands are %d and %d, now type initial of desired operation:\n");
if(scanf("%c", &i) == 1)
{
}
}
It's important to check that scanf() has succeeded before relying on the return value.

use scanf(" %c",&i);
there is new line character is present in buffer,so it is not asking for any input and storing it in i.

s1 & s2 are not declared which you are trying to read into them.
I feel they should be num1 & num2 which you been declared as integers.
After printf you just read a char value into i using scanf and main ends doing nothing.

Related

Encountering undefined behavior on a function to add up numbers below 10

I am encountering UB in the terminal with my current code when the input contains comma, dot or non-only-numeric character. I am confused why that is happening.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
float tizAlatti(int inputCount);
int main(){
int inputNumber;
printf("Number of input elements: ");
scanf("%d", &inputNumber);
if(inputNumber % 1 != 0 && (isdigit(inputNumber) == 0)){
printf("Error encountered.");
exit(1);
}
printf("\n%.2f", tizAlatti(inputNumber));
}
float tizAlatti(int inputCount){
float arr[inputCount], input = 0;
printf("\n");
for(int i = 0; i<inputCount; i++){
printf("Element %d: ", i+1);
scanf("%f", &arr[i]);
if(arr[i] < 10){
input+= arr[i];
}
}
return input;
}
Here I got this output for "h" input. It's not its ASCII code value, which was a false assumption by me.
I also got this output for "5.6" input.
I worked out that the issue lays somewhere in the if() part in the main() function, as the tizAlatti function gets invoked in the main for an input, but I don't know what this problem exactly is. Any help is highly appreciated!
I am encountering UB in the terminal with my current code when the input contains comma, dot or non-only-numeric character.
Neither scanf("%d", &inputNumber) nor scanf("%f", &arr[i]); ever read these characters*1, so they remain in stdin until something does read them. This also blocks following input.
As scanf("%d", &inputNumber) and scanf("%f", &arr[i]) then do not assign inputNumber or arr[i], that value is indeterminant leading to subsequent trouble.
Check the return value of scanf() and if not 1, exit or use other code to read/consume the non-numeric input and try again.
Even better, use fgets() to read a line of user input and stop using scanf() until you know why it is bad.
*1 '.' as a decimal point is read by scanf("%f", &arr[i]).

Even numbers from an array (C)

I'm new to C and I can't figured it out why this code does not work properly.
The whole idea was to enter few numbers and output amount of even numbers.
int n, p;
printf("How many numbers would you like to enter?\n");
scanf("%d", &n);
int array[n];
printf("Enter your numbers\n");
for (int i = 0; i == n; i++) {
scanf("%d\n", &array[i]);
if (array[i] % 2 == 0) {
p++;
}
}
printf("Amount of even numbers: %d", p);
There are multiple problems in your code fragment:
p is uninitialized: the behavior is undefined. You must initialize p as int p = 0;
scanf("%d\n", &array[i]); will consume any trailing white space, forcing the user to type the next value before returning. Just use scanf("%d", &array[i]);
the loop test is incorrect: i == n is false at the first iteration unless n is 0. You should write:
for (int i = 0; i < n; i++) {...
Note that you do not need to store the input values into an array but you should check the return value of scanf() to avoid undefined behaviour on invalid input:
#include <stdio.h>
int main() {
int n, val, p = 0;
printf("How many numbers would you like to enter? ");
if (scanf("%d", &n) != 1) {
printf("invalid input\n");
return 1;
}
printf("Enter your numbers: ");
for (int i = 0; i < n; i++) {
if (scanf("%d", &val) != 1) {
printf("invalid input\n");
break;
}
if (val % 2 == 0) {
p++;
}
}
printf("Amount of even numbers: %d\n", p);
return 0;
}
There are multiple issues:
You haven't given an initial value for the variable p. Many programming language may give it a default value of 0 by default, by that's not the case with C/C++. In C/C++, the default value for a variable is simply a garbage value. What you're doing is incrementing a garbage value instead of incrementing a zero.
Your loop condition is wrong. You should loop while i < n, not i == n.
If you fixed these 2 points, your code will work. But wait! that doesn't mean the code is good. There are still potential issues:
NEVER create an array of unknown size on the stack. You don't know how large number the user may enter. Your program will crash, which is bad.
You're not using the array anyways. You can just take the number and increment your counter.
C is an unsafe language. Unlike many other languages, it does not do anything for you unless you tell it to. I the line:
int n,p
You create two variables, this tell the compiler to create space for them on the stack. What is does not tell the compiler is what to put into those variables. What ends up happening is whatever was in those memory locations at the time end up in the variables. This can be literally anything and in C terminology is undefined behaviour. (In C undefined is the same as very bad).
What you need to do to fix things is to use:
int n = 0;
int p = 0;
You can save the work of initializing n since scanf does it for you but until you are sure it is a good idea, always initialize variables.
As an aside, be careful with scanf you case is fine but when dealing with strings, scanf might overflow your variable. To be safe use sscanf. This allows you to specify your size.

Unexpected behavior after scanf() in do..while loop

Hi I am studying C language by myself.
My question is, is there something I missed which need to know when working with scanf() that takes char value?
To practice do...while loop, I wrote some code like below but it did not work as I expected.
#include <stdio.h>
int main()
{
char y_or_n;
int x =1;
int y;
do
{
printf("ENTER A NUMBER\n");
scanf("%d", &y);
printf("THE NUMBER WILL BE ADDED TO x WHICH IS %d\n", x);
x = x+y;
printf("x TURNED INTO %d\n", x);
printf("KEEP DOING THIS?(y/n)\n");
scanf(" %s", &y_or_n);
printf("x is %d\n", x);
}
while(y_or_n =='y');
printf("GOOD BYE\n");
return 0;
}
For the first loop, it worked as I expected.
For example, when I entered 7, x turned into 8. But after scanf() was executed, value of x was changed into 0.
So from second loop, value of x changed temporarily into value of y and changed again into 0.
I guessed that there is something wrong with scanf() function and modified the code slightly: changed type of y_or_n into integer so that scanf() takes integer value.
The modified code is like below
include <stdio.h>
int main()
{
int y_or_n;
int x =1;
int y;
do
{
printf("ENTER A NUMBER\n");
scanf("%d", &y);
printf("THE NUMBER WILL BE ADDED TO x WHICH IS %d\n", x);
x = x+y;
printf("x TURNED INTO %d\n", x);
printf("KEEP DOING THIS?(y/n)\n");
scanf(" %d", &y_or_n);
printf("x is %d\n", x);
}
while(y_or_n ==1);
printf("GOOD BYE\n");
return 0;
}
This time the code worked as I expected.
Value of x was not changed into 0 even after an execution of scanf() and every time I entered a number that number was added to x.
If my question is not clear, please let me know.
Thank you for reading.
%s is for reading null-terminated strings, so passing pointer to one-byte buffer for that is bad.
It seems the variable x is placed just after the variable y_or_n on the memory and writing of terminating null-character by scanf() is setting value of x to 0.
To read one character, use %c instead.
char y_or_n;
/* ... */
scanf(" %c", &y_or_n);

Scanf Runtime error, have to ctrl-alt-delete

int main()
{
double a = 1;
double b = 3;
int n = 128;
int answer = 0;
printf("select an option(1, 2) ");
scanf("%d", answer);
double y = calcIntegral (answer, a, b, n);
printf("%f \n", y);
system("pause");
return 0;
}
it gets to Scanf and then if accepts the answer but stalls completely and I have to force the task to end. What's going on? This is identical to other programs I've written, I think. I tried using %i as well, and using a char instead of a double for the variable "answer". It says it can't access the memory.
For scanf with modifier d, it matches an optionally signed decimal integer, and the next pointer must be a pointer to int. Says the standard. Also make sure always check scanf return value.
int ret = scanf("%d", &answer);
if (ret != 1) {
// failed to input the number
}
When using scanf(), the variable you read has to be a pointer . So your statement :
scanf("%d", answer);
should be :
scanf("%d", &answer);
as you have declared answer to be an int, so its memory address is a pointer to an int.
On the other hand, if you wanted to read a string and had declared :
char *str;
allocating some memory for it, then the statement would be :
scanf("%s", str);
as str is declared as a pointer to char.

Validate Input to a C Program

i have a c program in which i am accepting 2 numbers as input.
How do i validate if input entered is numbers only and not characters.
void main()
{
int a,b;
printf("Enter two numbers :");
scanf("%d%d",&a,&b);
printf("Number 1 is : %d \n Number 2 is : %d",a,b);
}
[Edit] Added Sample Code
Besides the other interesting suggestions (especially the one with scanf), you might also want to use the isdigit function:
The isdigit() function shall test
whether c is a character of class
digit in the program's current locale
note that this function examines only ONE char, not an entire bunch of them.
It is always good practice to resort to already-built functions; there are intricacies you might not be aware of even in the simplest task, and this will make you a good programmer overall.
Of course, in due time you might want to look at how that function works to get a good grasp of the underlying logic.
scanf returns the number of items that it has successfully scanned. If you asked for two integers with %d%d, and scanf returns 2, then it successfully scanned both numbers. Any number less than two indicates that scanf was unable to scan two numbers.
int main()
{
int a,b;
int result;
printf("Enter two numbers :");
result = scanf("%d%d",&a,&b);
if (result == 2)
{
printf("Number 1 is : %d \n Number 2 is : %d",a,b);
}
else if (result == 1)
{
// scanf only managed to scan something into "a", but not "b"
printf("Number 1 is : %d \n Number 2 is invalid.\n", a);
}
else if (result == 0)
{
// scanf could not scan any number at all, both "a" and "b" are invalid.
printf("scanf was not able to scan the input for numbers.");
}
}
One other value that scanf may return is EOF. It may return this if there is an error reading from the stream.
Also note that main returns int, but you have it declared with void return.
Read user line of text input as a string. This greatly simplifies error handling.
int a = 0, b = 0;
char buf[100];
for (;;) {
printf("Enter two integers :");
if (fgets(buf, sizeof buf, stdin) == NULL) {
printf("Input closed\n");
break;
}
Then test the string for 2 ints with no following junk. Use sscanf() (simple) , strtol() (more robust), etc.
int n; // %n records where scanning stopped
if (sscanf(buf, "%d%d %n", &a, &b, &n) == 2 && buf[n] == '\0') {
printf("Number 1 is : %d \n Number 2 is : %d", a, b);
break;
}
printf("<%s> is not 2 integers. Try again\n", buf);
}
More advanced code uses strtol() to validate and also detect excessively long lines of input.

Resources