Solved

Validate a string as a valid dollar amount.

Posted on 2003-12-09
5
660 Views
Last Modified: 2012-06-27
This has got to be an easy question, but I just learning C++ for school. I need to validate a string to be a valid price for an item and once it is validated, convert it to a float. This is the code that I have so far. It accepts the price and enters it into my array, but it always displays on screen that the price is invalid. Can someone tell me what I'm doing wrong, or if there is an easier way to accomplish this. It is very important that I figure this out today, as this is due tomorrow.

Thanks!
Adam


            for(int s = 0; s!=1;)
            {
                  char inputPrice[10];
                  
                  cout << "\nEnter the DVD price: ";
                  cin.getline(inputPrice, 10);
                  int len = strlen(inputPrice);

            if (len > 5)
                  cout << "Price cannot be exceed $99.99" << endl << endl;

            if (len = 4 && !ispunct(inputPrice[1]))
                  cout << "Invalid Price" << endl << endl;

            if (len = 4 && (!isdigit(inputPrice[0]) ||
                        !isdigit(inputPrice[2]) ||
                        !isdigit(inputPrice[3])))
                  cout << "Invalid Price" << endl << endl;

            if (len = 5 && !ispunct(inputPrice[2]))
                  cout << "Invalid Price" << endl << endl;

            if (len = 5 && (!isdigit(inputPrice[0]) ||
                        !isdigit(inputPrice[1]) ||
                        !isdigit(inputPrice[3]) ||
                        !isdigit(inputPrice[4])))
                  cout << "Invalid Price" << endl << endl;
                  

            else
                  {      
                  tempPrice = atof(inputPrice);
                  s++;
                  }
            }
            theDVD.Price = tempPrice;
0
Comment
Question by:verbal11
  • 2
  • 2
5 Comments
 
LVL 1

Expert Comment

by:meow00
Comment Utility
Hello .... would u mind posting the whole code ... eg. How u define theDVD class ....
hard to debug and compile to check if the result works like this .... thanks !
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 150 total points
Comment Utility
>>Can someone tell me what I'm doing wrong

1st of all, the BIGGEST mistake is

if (len = 4 && !ispunct(inputPrice[1]))

as this *assigns* '4' to 'len' instead of a comparison. The easiest validation method would be

#include <stdlib.h>

//...

while ( 1) {

    cin.getline(inputPrice, 10);
    int len = strlen(inputPrice);

    if (len > 5) {

        cout << "Price cannot be exceed $99.99" << endl << endl;

        continue; // next try
    }

    char* pc = NULL;

    if ( '$' != inputPrice[0]) {

        cout << "Price must start with '$'" << endl << endl;

        continue; // next try
    }

    double dPrice = strtod ( &inputPrice[1], &pc); // start conversion to 'double' after the '$' marker

    if ( 0 != *pc) { // conversion stopped at sth. else but the terminating zero

        cout << "Price has invalid format" << endl << endl;

        continue; // next try
    }

    theDVD.Price = (float) dPrice;

    break; // we got a valid price, stop loop

}


0
 
LVL 2

Author Comment

by:verbal11
Comment Utility
Ok, here's all the code. I know there are other problems with the code, but don't worry about those mistakes...unless of course you want to fix everything :)

#include <iostream>
#include <iomanip>
#include <ctype.h>
#include <string.h>

using namespace std;

const int MAXRECS = 3;            //max no. of records.
const int MAXTITLE = 35;      //max no. of characters in title.
enum DVDGenre{ACTION, MYSTERY, COMEDY, ROMANCE}Genre;


struct DVD
{
      char Title[25];
      int Year;
      double Price;
      int Genre;
};

void populate(struct DVD &theDVD);
void display(struct DVD &theDVD, int);

int main()
{
      struct DVD myDVD[3];

      for (int i=0; i<3; i++)
            populate(myDVD[i]);

      for (int i=0; i<3; i++)
            display(myDVD[i], i);

}

void populate(DVD &theDVD)
{
      
            int tempYear=0;
            double tempPrice;
            char TempTitle[MAXTITLE] = "";
            int inputGenre;

            cout << "Enter the movie title: ";
            cin.getline(TempTitle,MAXTITLE);
            for(int v = 0; TempTitle[v] != '\0'; v++) //convert title to uppercase
                  TempTitle[v] = toupper(TempTitle[v]);
            strcpy(theDVD.Title, TempTitle);
            
            
            for(int x = 0; x!=1;) //year validation
            {
                  char inputYear[10]="";
                  
                  cout << "\nEnter the year of release: ";
                  cin.getline(inputYear, 10);
                  if(strlen(inputYear) != 4)
                        cout << "\nInvalid year" << endl << endl;
                        
                  if (!isdigit(inputYear[0]) ||
                        !isdigit(inputYear[1]) ||
                        !isdigit(inputYear[2]) ||
                        !isdigit(inputYear[3]))  
                        cout << "\nInvalid year" << endl << endl;
                  
                  tempYear = atoi(inputYear);

                  if(tempYear < 1910 || tempYear > 2003)
                        cout << "\nInvalid year" << endl << endl;
                  else x++;
                        
            }
            theDVD.Year = tempYear;
            

            for(int s = 0; s!=1;)
            {
                  char inputPrice[10];
                  
                  cout << "\nEnter the DVD price: ";
                  cin.getline(inputPrice, 10);
                  int len = strlen(inputPrice);

            if (len > 5)
                  cout << "Price cannot be exceed $99.99" << endl << endl;

            if (len = 4 && !ispunct(inputPrice[1]))
                  cout << "Invalid Price" << endl << endl;

            if (len = 4 && (!isdigit(inputPrice[0]) ||
                              !isdigit(inputPrice[2]) ||
                              !isdigit(inputPrice[3])))
                  cout << "Invalid Price" << endl << endl;

            if (len = 5 && !ispunct(inputPrice[2]))
                  cout << "Invalid Price" << endl << endl;

            if (len = 5 && (!isdigit(inputPrice[0]) ||
                              !isdigit(inputPrice[1]) ||
                              !isdigit(inputPrice[3]) ||
                              !isdigit(inputPrice[4])))
                  cout << "Invalid Price" << endl << endl;
                  

            else
                  {      
                  tempPrice = atof(inputPrice);
                  s++;
                  }
            }
            theDVD.Price = tempPrice;


            
            do
            {
                  cout << "[0]ACTION  [1]MYSTERY  [2]COMEDY  [3]ROMANCE" << endl;
                  cout << "Choose the genre: ";
                  cin >> inputGenre;
                  

            }while(inputGenre > 3 || inputGenre < 0);

            theDVD.Genre = inputGenre;
      
}
void display(DVD &theDVD, int i)
{
      
            cout << endl << endl <<setiosflags(ios::left)
                  << setw(8) << i << "  " << theDVD.Title
                  << setw(5) << theDVD.Year << setw(6) << theDVD.Price << "  ";
                  if(theDVD.Genre = 0)
                        cout << "ACTION";
                  else if(theDVD.Genre = 1)
                        cout << "MYSTERY";
                  else if(theDVD.Genre = 2)
                        cout << "COMEDY";
                  else if(theDVD.Genre = 3)
                        cout << "ROMANCE";



            return;
}

0
 
LVL 1

Accepted Solution

by:
meow00 earned 200 total points
Comment Utility
Okay ... in the following part :
------------------------------
    if (len > 5)
               cout << "Price cannot be exceed $99.99" << endl << endl;

          if (len == 4 && !ispunct(inputPrice[1]))
               cout << "Invalid Price" << endl << endl;

          if (len == 4 && (!isdigit(inputPrice[0]) ||
                         !isdigit(inputPrice[2]) ||
                         !isdigit(inputPrice[3])))
               cout << "Invalid Price" << endl << endl;

          if (len == 5 && !ispunct(inputPrice[2]))
               cout << "Invalid Price" << endl << endl;

          if (len == 5 && (!isdigit(inputPrice[0]) ||
                         !isdigit(inputPrice[1]) ||
                         !isdigit(inputPrice[3]) ||
                         !isdigit(inputPrice[4])))
               cout << "Invalid Price" << endl << endl;
-----------------------------------------
  in the "if" statement, we should use "==" rather than "=". otherwise you are "assigning len to be 4", not "testing whether len equals 4 or not" .....

meow.....
 
   
0
 
LVL 2

Author Comment

by:verbal11
Comment Utility
Thanks for your help. Both of you told me what I was doing wrong. I accepted meow's answer because it solved with fewer changes to my existing code.

Thanks again!!
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now