Question:
C programming: I am sure the below given code is very clear as in what it does,not giving the desired output?
haseeb
2012-12-25 12:41:40 UTC
The code does not give desired output. Please help!


#include
int main()
{
int a;
int b;
int c;
while(1)
{
printf("What do you want to do: Press 1 for transaction, 2 for cash withdrawal, 3 for quit\n");
scanf("%d",&a);
if (a==1)
{


printf("You want to transact money\n");

printf("Write your amount");
scanf("%d",&b);
}


if (a==2)
{
printf("Write your amount");
scanf("%d",&c);

if(c<200 || c>200000)
printf("amount invalid");
else
printf("%d",c);
}

if(a==3)
break;

printf("Do you want to continue press y or n?");
while(scanf("%c")=='\n')
scanf("%c",&b);
if(b=='y')
continue;
if(b=='n')
break;

}

}
Three answers:
ʄaçade
2012-12-25 13:05:42 UTC
while (scanf ("%c") == '\n')



Here is a problem. Scanf does not return a character, "\n" or otherwise. It certainly does not return TWO characters (a backslash and an n as you seem to predict).



RETURN VALUE

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.



So this while loop is wrong. What you probably meant was to read all characters until a "\n" is detected.
roger
2012-12-27 08:13:05 UTC
your problem is here:





printf("Do you want to continue press y or n?");

while(scanf("%c")=='\n')

/// bzzzt ---^^^^^ you are using scanf improperly

scanf() returns the number of item scanned correctly NOT the item scanned

and you did not include the address of the variable who's value is to be used

scanf("%c",&b);/// bzzzt b is an int %c is for a single character

// change the type of b to char

(instead of

int b;

above say

char b;

so you can scan it in as a character NOT an int (even tho chars and ints are BOTH integers)

if(b=='y')

continue; // oops this just continues the while(scanf() ) loop not what you want

if(b=='n')

break; // this just breaks outa the while(scanf()) loop not what you want



}



this is better no while loop needed



printf("Do you want to continue press y or n?");



scanf("%c",&b);

if(b=='y')

continue;

if(b=='n')

break;
?
2016-12-01 08:15:05 UTC
a) void exchange(int); that's the prototype or the signature of the function b) The formal argument is an int variety, the truthfully argument is x with the cost of 10 c) The function exchange takes an int as parameter. The calling technique is by utilising fee. d) because of the fact the calling technique is by utilising fee, the function exchange does not exchange the parameter. hence the cost of x in substantial continues to be 10, as defined there.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...