c语言版本。
思路:建立一个字符串不断输入要”反“的目标字符串,再建立一个二维字符数组。用来一个字符数组存入一个单词,依次类推,然后倒着输出即可;
#include<cstdio>
int main()
{
char str[90][90];
int num = 0;
while(scanf("%s",str[num]) != EOF) { // 启动该键,在输入结束时,先打回车再ctrl+z,再回车。
num++;
}
for (int i = num - 1; i >= 0; i--) {
printf("%s",str[i]);
if (i > 0)
printf(" ");
}
return 0;
}
c++版本:
c++的版本其实思路与c的一致,只是因为本人初学c++,所以也尝试写了这个版本。
注意下面要输入结束时也如上,先打回车,再ctrl+z,再回车。
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
while(getline(cin,str)) {
string ans[90];
int h = 0, l = 0;
for (int i = 0; i < str.size(); i++) {
if (str[i] != ' ') {
ans[h][l] = str[i];
l++;
}
else {
h++;
l = 0;
}
}
for (int i = h; i >= 0; i--) {
cout << ans[i];
if (i != 0) {
cout << " ";
}
}
cout << endl;
}
return 0;
}
谢谢你的观看。