以下代码按预期用于前两个 getlines,在您输入 CC 变量后,它会进入无限循环,跳过 getlines 并且不等待输入。
这是一个示例运行:
输入持卡人姓名(或退出):John Doe
输入抄送号码:1234 1234 1234 1555
// 代码输出其他 couts 但不等待 getline 的输入。并重申 cout 声明。cin.ignore 似乎没有帮助或 cin.clear()
代码:
int main(int argc, char* argv[]) {
char CCName[64]; //cardholder name
char CCNumber[16]; //credit card number
char Expiration[8]; //expiration date
float Amount;
while (true) {
/* input processing block */
//gather card holder name
cout << "\nEnter card holder name (or quit): ";
cin.getline(CCName, 64);
//quit command processing
if (strcmp(CCName, "quit") == 1) {
cout << "\nYou successfully terminated the program\n";
//~ close(sockfd); //close socket
exit(EXIT_SUCCESS);
}
//gather credit card number
cout << "\nEnter CC number: ";
cin.getline(CCNumber, 16);
//error checking
if (strlen(CCNumber) != 15 && strlen(CCNumber) != 16) {
cout << "\nCredit card number must be 15 to 16 digits, try again: ";
cin.getline(CCNumber,16);
}
//gather expiration date
cout << "\nEnter expiration: ";
cin.ignore();
cin.getline(Expiration, 7);
//error checking
if (strlen(Expiration) != 7) {
cout << "\nExpiration date format mm/yyyy. Try again: ";
cin.getline(Expiration, 7);
}
//gather amount
cout << "\nEnter amount: ";
cin >> Amount;
}
return 0;
}