反向打印字符串

时间:2020-05-25 20:54:17

标签: c++

为什么我的代码无法正确获取我的所有输入?它只会将最后一个输入传递给我的函数并将其取反。我希望它保留用户的所有输入,直到键入quit为止。 我相信在读取q,quit或Quit时实际上并没有退出程序。 有人告诉我使用fgets(以前从未使用过)可以使用,但是我尝试使用它,但是它没有用,可能是没有正确使用。 fgets(userString,MAX, stdin)

示例输入:

Hello there
Hey
quit

您的输出:

yeH

预期输出:

ereht olleH
yeH

代码:

#include <cstring>
#include <iostream>
#include <string>
#define MAX 50
using namespace std;

void stringReverse(char userString[]);

int main() {
    char userInput[MAX];
    cin.getline(userInput, MAX);

    if(strcmp(userInput, "q") == 0) {
    }
    if(strcmp(userInput, "quit") == 0) {
    }
    if(strcmp(userInput, "Quit") == 0) {
    } else {
        cin.getline(userInput, MAX);
    }
    cin.getline(userInput, MAX);

    stringReverse(userInput);
    cout << userInput << endl;

    return 0;
}

void stringReverse(char userString[]) {
    for(size_t i = 0; i < strlen(userString) / 2; i++) {
        char temp = userString[i];
        userString[i] = userString[strlen(userString) - i - 1];
        userString[strlen(userString) - i - 1] = temp;
    }
}

2 个答案:

答案 0 :(得分:0)

我可以在您的问题中看到您在错误的位置使用了break。我建议您更正代码。

此外,您可以使用C的strrev()头文件中定义的string.h函数来直接反转字符数组(字符串)。无需为此编写其他函数。 例如。

char str[50] ;
getline(cin,str);
printf("%s",strrev(str));

此代码段将打印反转的字符串。

答案 1 :(得分:0)

main函数中没有循环,因此它将执行cin.getline(userInput, MAX); 3次并反转您输入的最后一个字符串,即quit

您可以使用while循环解决该问题:

int main() {
    char userInput[MAX];

    // loop for as long as cin is in a good state:
    while(cin.getline(userInput, MAX)) {

        // if any of the quit commands are given, break out of the while-loop:
        if(strcmp(userInput, "q") == 0 || strcmp(userInput, "quit") == 0 ||
           strcmp(userInput, "Quit") == 0)
        {
            break;
        }

        // otherwise reverse the string and print it
        stringReverse(userInput);
        cout << userInput << endl;
    }
}