c++根据偶数或奇数将单词放入堆栈



我正在编写一个程序,该程序根据用户输入的数字向用户随机提供一部电影。每部电影都有一个与之相关的数字,所以应该有两个堆栈,一个用于偶数,一个用于奇数。程序最终的工作方式是用户输入一个数字,如果是奇数,他们将从奇数池中获得一部电影。input。txt是这样的:

  1. DC明日传奇
  2. 冰河时代5:碰撞过程
  3. 佩小姐的特殊儿童之家
  4. 禁止帝国
  5. 零定理
  6. 《x战警:逆转未来》
  7. 木星提升
  8. The Mortal Instruments: City Of Bones
  9. The Age of Adaline
  10. 忧郁症

我想把这些电影分成那两个堆栈,所以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 ++;
}

最新更新