这些continue语句如何影响我的代码

How are these continue statements affecting my code?

本文关键字:影响 我的 代码 continue 语句 何影响 这些      更新时间:2023-10-16

我一直在Visual Basic 2013中编写这个小程序,试图为用户输入命令创建一种分层结构。基本上,我希望两个单词输入中的第一个能将程序引导到一个代码区域,并为第二个单词提供一组响应。在这个程序中,第一个单词可以是"人类"或"动物"。这些单词将程序引导到选择动物或人类类型的函数。

#include "stdafx.h"
#include <iostream>
#include <sstream>
void ifAnimal(std::string b) //This is the set of responses for a first word of "Animal"
{
  if (b == "pig")
   {
    std::cout << "It is a pig." << std::endl;
   }
  if (b == "cow")
   {
    std::cout << "It is a cow." << std::endl;
   }
}
void ifHuman(std::string b) //This is the set of responses for a first word of "Human"
{
  if (b == "boy")
   {
    std::cout << "You are a boy." << std::endl;
   }
  if (b == "girl")
   {
    std::cout << "You are a girl." << std::endl;
   }
}
int main()
  { 

while (1)
{
    std::string t;
    std::string word;
    std::cin >> t;
    std::istringstream iss(t); // Set up the stream for processing
    int order = 0; 

    //use while loop to move through individual words
    while (iss >> word)
    {
        if (word == "animal") 
        {
            order = 1;
            continue; //something wrong with these continues
        }
        if (word == "human")
        {
            order = 2;
            continue;
        }
        if (order == 1) 
        {
            std::cout << "The if statement works" << std::endl;
            ifAnimal(word);
        }
        if (order == 2) 
        {
            std::cout << "This one too" << std::endl;
            ifHuman(word);
        }
     }
   }
  return 0;
}

问题是,每当程序到达continue语句时,调用我的函数的if语句都不会被触发。根本不显示任何文本。如果continue语句被删除,则If语句会触发,但相应的函数包含错误的单词。我是不是没有意识到这些人在做什么?有没有更好的方法来完成我想做的事情?

continue的意思是跳过循环的其余部分,返回顶部。如果CCD_ 3被命中,那么CCD_。

看起来您希望word同时是两个单词,所以一旦执行ifAnimal(),就不会满足ifAnimal中的任何情况。当您调用该方法时,word永远不会是"pig""cow",因为只有当word等于"animal"时,您才会调用该方法,并且在此之后不会更改它。

Continue的意思是"立即转到循环的顶部,然后重新开始"。你根本不想那样。

  //use while loop to move through individual words
    while (iss >> word)
    {
        if (word == "animal") 
        {
            order = 1;
        }
        else if (word == "human")
        {
            order = 2;
        }
        if (order == 1) 
        {
            std::cout << "The if statement works" << std::endl;
            ifAnimal(word);
        }
        if (order == 2) 
        {
            std::cout << "This one too" << std::endl;
            ifHuman(word);
        }
     }