Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Validate a string as a valid dollar amount.

Posted on 2003-12-09
5
Medium Priority
?
707 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
5 Comments
 
LVL 1

Expert Comment

by:meow00
ID: 9907590
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 600 total points
ID: 9907660
>>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
ID: 9907663
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 800 total points
ID: 9907762
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
ID: 9907861
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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

670 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