当我运行程序时,结果相同

时间:2017-07-17 22:40:48

标签: c++11

#include <iostream>
using namespace std;
int main()
{
  bool result;
  char text[1000];
  cin>>text;
  int len=sizeof(text);
  for(int i = 0 ;i<len; ++i)
  {
    if(text[i]=='t' && text[i+1]=='r' && text[i+2]=='u' && text[i+3]=='e') 
        result = true;
    else if(text[i]=='f' && text[i+1]=='a' && text[i+2]=='l' && text[i+3]=='s' && text[i+4]=='e')
        result = false;

  }
  for(int i = 0 ;i<len; ++i)
  {
      if(text[i]=='n' && text[i+1]=='o' && text[i+2]=='t')
          result = !result;// i think here is the problem
  }
  if(result == true)
      cout<<"true"<<endl;
  else if(result == false)
      cout<<"false"<<endl;
return 0;

练习: 布尔值可以是True或False。给定一个少于1000个字符的字符串,其中一些空格分隔的非指令以True或False值终止,请计算布尔表达式。 但是当我运行程序时,结果总是如此。 请问你能告诉我问题出在哪里

1 个答案:

答案 0 :(得分:-1)

为什么不使用已有的东西?

#include <iostream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

int main()
{
  bool result;

  // Read the line
  std::string line;
  std::getline(std::cin, line);

  // Split the line at spaces (https://stackoverflow.com/a/237280/1944004)
  std::istringstream iss(line);
  std::vector<std::string> tokens{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};

  // Convert last element to bool
  if (tokens.back() == "true") result = true;
  else if (tokens.back() == "false") result = false;
  else throw std::invalid_argument("The last argument is not a boolean!");

  // Remove the last element
  tokens.pop_back();

  // Loop over the nots
  for (auto const& t : tokens)
  {
    if (t == "not") result = !result;
    else throw std::invalid_argument("Negation has to be indicated by 'not'!");
  }

  // Output the result
  std::cout << std::boolalpha << result << '\n';
}

Live example