My program only takes input for the first prompt and it excludes the succeeding ones, and instead, it just directly prints them.
#include <stdio.h>
int main(){
// Initialize
char cCurrencyA, cCurrencyB;
float fCurrencyA;
float fRate;
// Prompt user for currency names
printf("Enter a currency name: ");
scanf("%c%c", &cCurrencyA, &cCurrencyB);
// Prompt user for the current rate
printf("Enter the rate:");
scanf("%f", &fRate);
// Prompt user to enter value for currency A
printf("Enter value for %c", cCurrencyA);
scanf("%f", &fCurrencyA);
// Convert currency A to B
int nResult = fCurrencyA * fRate;
// Print the result
printf("%f%c is %d%c", fCurrencyA, cCurrencyA, nResult, cCurrencyB);
return 0;
}
Output:
Enter a currency name:USD PHP
Enter the rate:
Enter value for U:
0.000000U is 0S
CodePudding user response:
so you have major problems , you are scanning a whole string into only one
char
, that's wrong , you should dochar cCurrencyA[20], cCurrencyB[20];
notchar cCurrencyA, cCurrencyB;
to scan a string not only onechar
.when you are scanning using
scanf()
, use the quantifier%s
not%c
, as%c
will get only one character but%s
will scan a whole string.also to round the result , you could use
math
header file , by using the function calledlround()
, so do thisint nResult = round((double)fCurrencyA * fRate);
notint nResult = fCurrencyA * fRate;
as the lValue isint
while RValue isfloat
so you have to cast it.
and here the code edited :
#include <stdio.h>
#include <math.h>
int main(){
// Initialize
char cCurrencyA[20], cCurrencyB[20];
float fCurrencyA;
float fRate;
// Prompt user for currency names
printf("Enter a currency name: ");
scanf("s s", cCurrencyA, cCurrencyB);
// Prompt user for the current rate
printf("Enter the rate:");
scanf("%f", &fRate);
// Prompt user to enter value for currency A
printf("Enter value for %s", cCurrencyA);
scanf("%f", &fCurrencyA);
// Convert currency A to B
int nResult = lround((double)fCurrencyA * fRate);
// Print the result
printf("%f%s is %d%s", fCurrencyA, cCurrencyA, nResult, cCurrencyB);
return 0;
}
and here is the output :
Enter a currency name:USD PHP
Enter the rate:10.5
Enter value for USD10
10.000000USD is 105PHP
Process finished with exit code 0
CodePudding user response:
First line of input was 8 characters: "USD PHP\n"
.
scanf("%c%c", &cCurrencyA, &cCurrencyB);
only reads and saves the first 2 in cCurrencyA
, cCurrencyB
.
The remaining 6 are not numeric text for the next scanf("%f",...
so it does not assign anything and returns 0. Same for the next scanf("%f",...
.
Best to read a line of user input with fgets()
and then parse the string.
Yet if one must use the problematic scanf()
, read currency names as a string.
// char cCurrencyA, cCurrencyB;
char cCurrencyA[100], cCurrencyB[100];
// scanf("%c%c", &cCurrencyA, &cCurrencyB);
scanf("