Credit Card Validation

So here I am again with a similar question. Valid input is either: xxxx-xxxx-xxxx-xxxx or xxxx xxxx xxxx xxxx . I know the condition looks a bit messy, but when I tried to reduce it, it also didn't work. I should be able to type in 16 numbers with either spaces or dashes in between each 4 digits. And based on that, if it's a valid input, say that, if not, say invalid.
What am I doing wrong?

#include<iostream>
#include<vector>
#include<string>
using namespace std;

int main()
{
vector<int> cc;
int i,num;
while((num=='0' || num=='1' || num=='2' || num=='3' || num=='4' || num=='5' || num=='6' || num=='7' || num=='8' || num=='9')&& ((cc[4]==' ' && cc[9]==' ' && cc[14]==' ')||(cc[4]=='-' && cc[9]=='-' && cc[14]=='-')) )
{
for(i=0;i<18;i++)
{
cin>>num;
cc.push_back(num);
}
}

if(cc.size()==18)
{
cout<<"Valid";
}
else
{
cout<<"Invalid";
}


system("pause");
return 0;
}
nice information
Yes. You can thank my teacher since he's the one who assigned this. So, how should I accomplish this problem? Is there something small I'm doing wrong, or do I change my tactic, or..?
The condition isn't just messy, it's wrong.

To begin with, num has some random value (and is not a char) and neither cc[4], nor cc[9], nor cc[14] are valid indices into your empty vector.




A better approach would be to have the user enter the whole thing as a string, then use string functions to check whether the input is valid. cin won't work for that because it only reads up until it encounters whitespace, so try getline instead. This would avoid the very messy while condition. You wouldn't need a vector, just use a string.

Can you please use code tags - the <> button on the right.

Try to avoid the using namespace std; you can do one of these instead:

1. Put these after the #include statements

1
2
3
4
5
using std::cout;
using std::cin;
using std::endl;
using std::string;
//similar for whatever std thing you want to use 


2. Put std:: before each std thing in your code. Example :

 
std::cout << "Testing " << std::endl;


I prefer the first - I would rather have 20 of those at the start of the file rather than 200 std:: throughout.

However, a lot of people prefer the second.

Don't use system("pause"); there is an article on this site all about why that is bad. Go to the articles link at the top left of this page. While you are there, check out the reference section as well.

HTH
Topic archived. No new replies allowed.