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

How are these continue statements affecting my code?

我一直在 Visual Basic 2013 中开发这个小程序,试图为用户输入命令创建一种分层结构。基本上,我希望双词输入中的第一个将程序定向到一个代码区域,其中包含对第二个词的一组响应。在这个程序中,第一个词可以是 "human" 或 "animal." 这些词指示程序函数 select 动物或人的种类。

#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 语句会触发,但相应的函数会出现错误的词。我不知道那些继续在做什么吗?有没有更好的方法来完成我想做的事情?

继续意味着 "Go immediately to the top of the loop, and start over again"。你根本不想要那个。

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

continue 的意思是跳过循环的其余部分并返回顶部。如果 continue 被命中,continue 语句之后的任何内容都不会被执行。

看起来你希望你的 word 同时是两个词,所以一旦你执行 ifAnimal() none ifAnimal 中的案例将是遇见了。当您调用该方法时,word 永远不会是 "pig""cow",因为您只会在 word 等于 "animal" 时调用该方法,而您不会之后就不要改了。