尝试让程序在键入“退出”时退出。 C++

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

我目前正在尝试让我的程序在键入“退出”时退出,但它不会工作并且什么也没有发生。有时它会终止它。我对所有编码都非常陌生,因此不胜感激。这是我为它写的:

int main(){
    int length = 1024;
    char *mainInput = new char[length];
    Start(mainInput, length - 1);
    delete []mainInput;
    return 0;
}

void Start(char* &input, int length){
    char message[] = "Type quit to exit program. Type any other line to begin: ";
    ReadLine(input, length, message);
    if(strstr(input, "quit")){
        cout << "Terminating program." << endl;
        exit(0);
    }
    cout << "Youre string is: " << input << endl;
    int option;
    cout << "Choose option: (Vowels_Vs_Consonants (1), Letter_Swap (2), Flip_String (3), Palindrone_Detector(4), Words_Frequency(5)): ";
    cin >> option;
    switch(option){
        case 1:
            vowels_vs_consonants(input);
            break;
        case 2:
            letter_swap(input);
            cout << "Our new string: " << input << endl;
            break;
        case 3:
            reverse_string(input);
            cout << "Original: " << input << endl;
            break;
        case 4:
            if(is_palindrome(input)){
                cout << "It is a palindrome." << endl;
            }
            else{
                cout << "It is not a palindrome." << endl;
            }
            break;
        case 5:
            word_frequency(input);
            break;
        default:
            Start(input, length);
            break;
    }
    cin.clear();
    Start(input, length);
}


我试过弄乱大写因子,但我无法编译它。

c++ exit
1个回答
0
投票
#include <iostream>

void ReadLine(char*& input, int length, char* message) {
    std::cout << message;
    //std::cin >> input; // this line does not work if you want the cstring to have space. Example :"asd 123" would only return "asd"
    std::cin.getline(input, length);
    //std::cin.getline(input, length, '\n');
}

// I did not change anything below, so I assume the problem is in your ReadLine()
void Start(char*& input, int length) {
    char message[] = "Type quit to exit program. Type any other line to begin: ";
    ReadLine(input, length, message);
    if (strstr(input, "quit")) {
        std::cout << "Terminating program." << std::endl;
        exit(0);
    }
    std::cout << "Youre string is: " << input << std::endl;
    std::cin.clear();
    Start(input, length);
}

int main() {
    int length = 1024;
    char* mainInput = new char[length];
    Start(mainInput, length - 1);
    delete[]mainInput;
    return 0;
}

我认为您的 ReadLine() 函数有问题。由于我不知道你的 ReadLine() 包含什么,我假设其他评论员所说的是这种情况(你也在阅读换行符)。上述解决方案有效,但我不知道这是否是您遇到的问题。

我能想到的另一个解决方案是:

  1. 修剪“输入”变量以去除“strstr”之前末尾的换行符。
  2. 添加一个 cin.ignore(' ');某处

(注意:我复制了您的代码并删除了其中一些以使我的解决方案更具可读性。我是一名学生,所以我的代码可能也不是最合理/优化的)

希望对您有所帮助!

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.