C ++ While循环无故中断

#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语句。

wtycs 回答:C ++ While循环无故中断

尝试一下:

#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";
   }
}
本文链接:https://www.f2er.com/3141130.html

大家都在问