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
Solved

Validate a string as a valid dollar amount.

Posted on 2003-12-09
5
681 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
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 150 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 200 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
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.

808 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