反向打印字符串
Print string in reverse
为什么我的代码没有正确抓取我所有的输入?它只将最后一个输入传递给我的函数并反转它。我希望它保留用户的所有输入,直到输入退出。 我相信当 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));
此代码片段将打印反转的字符串。
相关文章:
- 有没有办法将字符串打印为文字?
- 如何通过标准字符串打印 ostream 变量的值?
- 这个随机字符串打印代码有什么问题?
- 比较 C++ 字符串打印中的两个整数数组
- 在C++中从后缀表达式字符串打印单个操作
- 没有得到 ASCII 编号 = 7 的字符串打印输出
- C++字符串到字符串打印不正确,无法获取 unicode 路径
- 如何从数组 c++ 中的字符串打印第 N 个字符
- 将 LPCWSTR 字符串打印到文件
- C++正在将DWORD_PTR*字符串打印到文件中
- 使用#define字符串打印f和警告
- 使用格式字符串打印类
- 如何将字符转换为字符串,并从字符串打印到main函数
- 将vector中结构体的成员字符串打印到cout流
- fprintf() / std::cout 不会将部分字符串打印到 stdout/stderr
- 为什么ostream为定义为' volatile char[] '的字符串打印' 1 ' ?
- c++文件读取和字符串打印
- 如何使用一个字符串打印此unicode行
- 按字符串打印日期
- 如何用c++将字符串打印到控制台