Create program and prompt me to enter a dollar amount between 0 and 999.99999 as
ID: 3752634 • Letter: C
Question
Create program and prompt me to enter a dollar amount between 0 and 999.99999 as a C-string or X to exit. Loop unit I enter X to exit.
Use a C-string for the input amount and related method processing. Review section 10.4. This implies you will have the following:
#include <cstring>
#include <string> may be needed in Visual Studio, but still use C-String functions.
Create a method that will use the functions described in Chapter 10. It is OK to use a globally defined char array. You must call this method to produce the formatted results. The program must modify or build a C-String in this format. Display the C-String created.
1. Include leading $ sign.
2. Must have a single decimal point with 2 digits after the decimal. If the amount had extra digits, then the result is a truncated value.
Explanation / Answer
Code:
#include <iostream>
#include<cstring>
char amount[9]; //global array declaration
int main() {
char dollorSign[10] = {'$'}; //local variable declaration
char afterdecimal[3];
char resultedAmount[10];
int i = 0;
int lengthAfterDecimal = 0;
int lengthOfAmount = 0;
int DifferencebWdecimalPart = 0;
printf("Enter the amount ");
scanf("%s", &amount); // Reading input from STDIN
strcat(dollorSign,amount); // Concatinating $ sign with the amount entered.
lengthOfAmount = strlen(dollorSign); //getting length of concatinated string
char *amountAfterDecimmal = strchr(dollorSign, '.'); //getting substring devided with .
if(amountAfterDecimmal == NULL) //checking if string contains any decimal value
{
strcat(dollorSign,".00"); //if not, inserting decimal values t string
lengthOfAmount = strlen(dollorSign);//getting updated length of string
amountAfterDecimmal = ".00";
}
lengthOfAmount = strlen(dollorSign);
lengthAfterDecimal = strlen(amountAfterDecimmal);
DifferencebWdecimalPart = lengthOfAmount - lengthAfterDecimal;
for(i = 0 ; i < DifferencebWdecimalPart + 3; i++) //looping through the string
{
if((dollorSign == NULL) || (dollorSign[i] == ''))//checking if any value is there at index i
{
dollorSign[i] = '0'; // if index i has no value, inserting 0
}
resultedAmount[i] = dollorSign[i]; //creating a new resulted string
}
printf("Result amount is %s ", resultedAmount); //printing the resulted string
}
input:
9243.596
output:
Result amount is $9243.59
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.