【问题标题】:C++ While loop breaks for no reasonC++ While 循环无故中断
【发布时间】:2019-11-07 23:15:20
【问题描述】:
#include <bits/stdc++.h>
#include <iostream>

using namespace std;

int main() {
    string vowel[] = {"b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "z"};
    string a;

    while (a != "quit!") {
        int b = 1;
        cin >> a;
        for (int i = 0; i < 20; i++) {

            if (a.length() > 4 && a.substr(a.length() - 3 ) == vowel[i] + "or") {
                a[a.length() - 2] = 'o';
                a[a.length() - 1] = 'u';
                a += 'r';
                cout << a << "\n";
                b = 0;
                break;
            }
            //cout << i;
        }

        if (b == 1) {
            cout << a << "\n";
        }
    }
}

由于某种原因,如果您输入一个长度大于 4 且不以辅音 +“或”结尾的字符串,整个程序就会停止。该程序甚至从不进入 if 语句。

【问题讨论】:

  • 您是在谈论您的 while 还是 for 循环?因为您的描述现在谈论的是 for 循环,但您的标题指的是外部 while 循环
  • 您的程序可能会崩溃,因为您的数组中的元素少于 20 个。
  • 哦,哈哈,非常感谢
  • 改用vector,然后使用size()方法。
  • string vowel[]:你是说consonant吗?

标签: c++ string


【解决方案1】:

试试这个:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

bool endswith(const string& a, string b) {
   return (b == a.substr(a.length() - b.length()));
}

bool isconsonant(char c) {
   vector<char> vowels = { 'a', 'e', 'i', 'o', 'u','y' };

   for (size_t i=0; i < vowels.size(); i++) {
      if (vowels[i] == c)
         return false;
   }

   return true;
}

int main() {
   string a;

   while (a != "quit!") {
      cin >> a;

      if ((a.length() > 4) && isconsonant(a[a.length()-3]) && endswith(a, string("or")))
            a = a.substr(0, a.length() - 2) + "our";

      cout << a << "\n";
   }
}

【讨论】:

  • 这是一个纯代码的答案。由于它们有导致Cargo Cult Programmers 的烦人倾向,因此您应该避免使用它们。您可以通过解释问题所在以及如何解决此问题来解决此问题。
猜你喜欢
  • 1970-01-01
  • 2017-11-14
  • 2022-07-31
  • 1970-01-01
  • 2020-08-17
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 2020-10-30
相关资源
最近更新 更多