我正在编写一个程序,该程序根据用户输入的数字向用户随机提供一部电影。每部电影都有一个与之相关的数字,所以应该有两个堆栈,一个用于偶数,一个用于奇数。程序最终的工作方式是用户输入一个数字,如果是奇数,他们将从奇数池中获得一部电影。input。txt是这样的:
- DC明日传奇
- 冰河时代5:碰撞过程
- 佩小姐的特殊儿童之家
- 禁止帝国
- 零定理
- 《x战警:逆转未来》
木星提升The Mortal Instruments: City Of Bones- The Age of Adaline
- 忧郁症
我想把这些电影分成那两个堆栈,所以stack_odd将有DC的传奇,佩小姐的,零定理等。
我不确定如何去把这些分成堆栈。下面是我打开文件的操作。
lass CReadFile {
protected:
Stack<string> stack_even;
Stack<string> stack_odd;
bool isblank(const std::string& s)
{ //True if s is empty or only contains space and/or TABs.
return s.find_first_not_of(" t")==std::string::npos;
}
void readFile (string filename)
{ ifstream file(filename);
string line;
// file opened?
if (! file) {
cerr << "can't open input file "" << filename << """<< endl;
exit(EXIT_FAILURE);
}
file.close();
}
我要做的是:
int a;
while(file >> a){
if(a % 2 == 0){
stack_even.push(a);
}else{
stack_odd.push(a);
}
}
声明一个count变量,并通过在每次迭代中增加count来检查是否出现偶数或奇数,参考下面的代码:
string a;
int count = 0
while (getline (file, a)){
if(count % 2 == 0){
stack_even.push(a);
}else{
stack_odd.push(a);
}
count ++;
}