我得到了任务:
cin.fail()
函数。有关邮政编码的信息:
我的代码如下:
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
void print_each_digit(int x)
{
if (x >= 10) print_each_digit(x / 10);
int digit = x % 10;
if (digit == 0) { cout << "||:::"; };
if (digit == 1) { cout << ":::||"; };
if (digit == 2) { cout << "::|:|"; };
if (digit == 3) { cout << "::||:"; };
if (digit == 4) { cout << ":|::|"; };
if (digit == 5) { cout << ":|:|:"; };
if (digit == 6) { cout << ":||::"; };
if (digit == 7) { cout << "|:::|"; };
if (digit == 8) { cout << "|::|:"; };
if (digit == 9) { cout << "|:|::"; };
}
int main()
{
char counter;
do {
int zip;
cout << "Please enter a zip code: "; cin >> zip; cout << endl;
cout << "|"; print_each_digit(zip); cout << "|" << endl;
if (cin.fail()) { cout << "The zip code you entered does not exist."; } {return 0;};
if (zip < 0 || zip > 100000) { cout << "The zip code you entered does not exist."; } { return 0;};
cout << "Would you like to continue? (y,n) "; cin >> counter;
} while (counter == 'y');
return 0;
}
我能够将邮政编码数字正确地输入到条形码中。但是,我的程序有两个问题。
如何修改我的代码,以便它可以计算校验位(邮政编码中每个数字的总和)?我不允许在char,string和int之间使用转换,因此无法使用get.substr()
进行计算。
我注意到我没有正确应用条件cin.fail()
。如何使它满足帖子开头列出的条件?