while循环多次询问是否正确[关闭]

问题描述 投票:0回答:0

程序必须接受输入,直到最后三个字符为“结束”。但它会问三遍,即使它是否持续结束。它是用 for 循环编写的,因为结束字控制应该不区分大小写

Enter the source string: cars are fast end
Enter the source string: Enter the source 
string: Enter the source string: Enter 
search string: 

另一个

Enter the source string: cars are fast
Enter the source string: Enter the source 
string: Enter the source string: 

在这里,我想立即搜索字符串输入,因为最后输入了end。但是它为源字符串打印了三次,这就是问题所在

    #include <iostream>
using namespace std;
#include <string>

int main()
{
    string source;
    string search;
    bool sourceCheck;
    int sourceLength;
    string lastThreeSource;
    string lowerLastThreeSource;
    int searchLength;
    bool searchCheck = false;
    string lastThreeSearch;
    while (sourceCheck == false) {
        cout << "Enter the source string: ";
        cin >> source;
        sourceLength = source.length();
        lastThreeSource = source.substr(sourceLength - 3,3);
        for (int i = 0; i < 3; i++) {
            lastThreeSource[i] = tolower(lastThreeSource[i]);
            
        }
        if (lastThreeSource == "end") {
            sourceCheck = true;
            
            
        }
        else {
            sourceCheck = false;
        }
    }
    while (searchCheck == false) {
        cout << "Enter search string: ";
        cin >> search;
        searchLength = search.length();
        
        if (search[searchLength - 1] == '+' || search[searchLength - 1] == '*' || search[searchLength - 1] == '.' || search[searchLength - 1] == '**') {
            searchCheck = true;
        }
        else {
            searchCheck = false;
        }
    }

}
c++ for-loop while-loop case-insensitive
© www.soinside.com 2019 - 2024. All rights reserved.