credit card validation



My errors are:
note: No constructor could take the source type, or constructor overload resolution was ambiguous

: error C2664: 'int sumOfOddPlace(const std::string &)': cannot convert argument 1 from 'std::string *[17]' to 'const std::string &'

note: Reason: cannot convert from 'std::string *[17]' to 'const std::string'

note: No constructor could take the source type, or constructor overload resolution was ambiguous

Home work question is:Write a program that prompts the user to enter a credit card number as a string. Display whether the number is valid. Design your program to use the following functions:

// Return true if the card number is valid
bool isValid( const string& cardNumber )

// Get the result from Step b)
int sumOfDoubleEvenPlace( const string& cardNumber )

// Return this number if it is a single digit, otherwise
// return the sum of two digits
int getDigit( int number )

// Return sum of odd-place digit in the card number
int sumOfOddPlace( const string& cardNumber )

// Return true if substr is the prefix for card number
bool startWith( const string& cardNumber, const string& substr )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
  #include <iostream>
#include <string>
using namespace std;


bool isValid(const string& cardNumber);

// Return this number if it is a single digit, otherwise, return the sum of the two digits 
int getDigit(int number)
{
	return number % 10 + (number / 10 % 10);
}

// Return sum of odd place digits in card number 
int sumOfOddPlace(const string& cardNumber)
{
	int result = 0;

	for (int i = strlen(cardNumber) - 1; i >= 0; i = i - 2)
	{
		result += cardNumber[i] - '0';
	}

	return result;
}

// Get the result from Step b on assignment 
int sumOfEvenPlace(const string& cardNumber)
{
	int result = 0;

	for (int i = strlen(cardNumber) - 2; i >= 0; i = i - 2)
	{
		result += getDigit((cardNumber[i] - '0') * 2);
	}

	return result;
}

int main()
{
	cout << "Enter a credit card number as a string: ";
	// hold 16 characters with a null terminator
	string& cardNumber[17]; 
	cin >> cardNumber;

	if ((sumOfEvenPlace(cardNumber) + sumOfOddPlace(cardNumber)) % 10 == 0)
		cout << cardNumber << " is valid" << endl;
	else
		cout << cardNumber << " is invalid" << endl;

	return 0;
}
Line 44 defines an array
 
    string& cardNumber[17];

You just need a single string.
 
    string cardNumber; 


Also, instead of the C strlen() function at lines 19 and 32, just use the size() member function
 
cardNumber.size() 

http://www.cplusplus.com/reference/string/string/size/
Last edited on
Thankyou!!
It works perfectly!
Topic archived. No new replies allowed.