反向打印字符串

Print string in reverse

本文关键字:字符串 打印      更新时间:2023-10-16

为什么我的代码没有正确抓取我所有的输入?它只将最后一个输入传递给我的函数并反转它。我希望它保留用户的所有输入,直到输入退出。 我相信当 q、退出或退出被阅读时,它实际上并没有退出程序。 有人告诉我使用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;
}
}

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

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

此外,您可以使用 C 头文件中定义的strrev()函数string.h直接反转字符数组(字符串(。没有必要为此编写不同的函数。 例如。

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

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