如果按 Enter 则执行某些操作,如果键入 End 则执行其他操作。 C++

时间:2020-12-29 12:36:38

标签: c++

今天我的问题如下:我对这段代码有什么要求,所以它只会在按下 Enter 时继续运行,并在写入“End”时终止。

如果它以任何方式相关,代码本身是为了写向后输入的任何单词,只是一个单词,而不是一个句子,它也有效(至少对我而言),唯一的问题是真正实现 Enter / 结束事情。

“它也有效”是指在插入“输入或结束”代码位之前的函数,谢谢。

代码:


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

void trade(string p);

int main(){
    
    string word;
    string input;
    int q = 0;
    while(q == 0){
    cout << endl << "Write a word!" << endl;
    cin >> word;
    trade(word);
    
    cout << "Press Enter to continue and write a new word. Type End to terminate." << endl;
    cin >> input;
    if(input == ""){
       q = 0;
    } else if(input == "End") {
        q == 1;
    } else {
cout << "None of that follows the rules, we will end it for you either way. << endl;
q == 1;
}
    
    }
}


void trade(string p){
    
    string temp;
    temp = p;
    int sizee = p.size();
    for(int i = 0; i < sizee/2; i++){
        swap(p[i], p[sizee - 1 - i]);
    }
    if(p == temp){
    cout << "New Word: " << p << " is actually the same" << endl;
    } else{
        cout << "New Word: " << p << endl;
    } 
}

1 个答案:

答案 0 :(得分:0)

使用 std::string str 读取 cin >> str 读取以空格分隔的非空单词。如果你只是按回车键,那只是空格,所以它会一直读到你输入一个词。因此,此后 str 永远不能为空。

如果您想读到换行符,请改用 getline(cin, str)

相关问题