这道题吧,就是要求把一行单词输入,然后倒着输出。在这个过程中有多种解决方案。
- 首先是单词存储结构的问题:可以使用char二维数组,也可以使用string数组/vector,也可以使用string stack。
- 然后是输入的问题:可以是把一整行输入之后再拆分,也可以是一个一个单词输入并存储。
- 最后是输出的问题:可以把数组翻转之后正序输出,也可以直接逆序输出,当然也可以不断输出栈顶并弹出了
方法1:C语言:用char二维数组存储
#include<stdio.h>
#include<string.h>
int main(){
char words[90][90];//字符二维数组,最多90个有90个字符的单词
int row=0,col = 0;// row:第几个单词 col:该单词的第几个字符
char str[90];
gets(str);//不确定单词数量,先读入整行,再进行分割
int len=strlen(str);
for (int i = 0; i <len;i++) {
if (str[i] != ' ') {
words[row][col++] = str[i];
}
else {
//遇到空格,结束该单词。将剩余字符读入下一个单词
words[row][col]='\0';
row++;
col = 0;
}
}
//将单词们逆序输出
for (int j = row; j >= 0; j--) {
printf ("%s",words[j]);
if (j > 0)printf (" ");
}
return 0;
}
方法二:C++:用string vector存储:
#include<vector>
#include<string>
#include<iostream>
using namespace std;
int main()
{
vector<string>words;
string str;
while(cin>>str){
words.push_back(str);
}
cout<<words[words.size()-1];
for(int i=words.size()-2;i>=0;i--){
cout<<" "<<words[i];
}
return 0;
}
方法三:C++:用string stack存储:
#include<stack>
#include<iostream>
using namespace std;
int main()
{
stack<string>words;
string str;
while(cin>>str){
words.push(str);
}
cout<<words.top();
words.pop();
while(!words.empty()){
cout<<" "<<words.top();
words.pop();
}
return 0;
}