简体   繁体   English

C++ 根据偶数或奇数将字放入堆栈

[英]C++ Placing words into stacks based on even or odd numbers

I am making a program that gives a random movie to the user based on what number they enter.我正在制作一个程序,根据用户输入的数字向用户提供随机电影。 Each movie has a number associated with it, so there should be two stacks, one for even and one for odd.每部电影都有一个与之相关的数字,因此应该有两个堆栈,一个用于偶数,一个用于奇数。 The way the program will work at the end is the user enters a number, and if it is odd they will get a movie from the pool of odd numbers.程序最后的工作方式是用户输入一个数字,如果它是奇数,他们将从奇数池中获得一部电影。 This is what my input.txt looks like:这就是我的 input.txt 的样子:

  1. DC's Legends of Tomorrow DC的明日传奇
  2. Ice Age 5: Collision Course冰河世纪 5:碰撞课程
  3. Miss Peregrine's Home for Peculiar Children佩雷格林小姐特殊儿童之家
  4. Forbidden Empire禁地帝国
  5. The Zero Theorem零定理
  6. X-Men: Days of Future Past X战警:逆转未来
  7. Jupiter Ascending木星上行
  8. The Mortal Instruments: City Of Bones圣杯神器:骸骨之城
  9. The Age of Adaline阿达琳时代
  10. Melancholia忧郁症

I want to split these movies into those two stacks, so stack_odd would have DC's Legends, Miss Peregrine's, The Zero Theorem, etc.我想将这些电影分成这两个堆栈,因此 stack_odd 将包含 DC 的传奇、佩雷格林小姐、零定理等。

I am unsure how to go about splitting these into the stacks however.但是,我不确定如何将这些拆分为堆栈。 This is what I do to open the file.这就是我打开文件的方法。

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();
            }

To do the stack would I go:要进行堆栈,我将 go:

int a;
while(file >> a){
    if(a % 2 == 0){
        stack_even.push(a);
    }else{
        stack_odd.push(a);
    }
}

Declare a count variable and check for even or odd occurance by incrementing count in each iteration, refer code below:声明一个计数变量并通过在每次迭代中增加计数来检查偶数或奇数出现,请参阅下面的代码:

string a;
int count = 0
while (getline (file, a)){
    if(count % 2 == 0){
        stack_even.push(a);
    }else{
        stack_odd.push(a);
    }
    count ++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM