运行结果:
涉及基础知识:
对于字符数组:
方法一:getline()
读入整行数据,使用回车键输入的换行符来确定输入结尾;
cin.getline(str, len),二者都适用于字符数组;
方法二:
cin.get(str, len)
两者都是读取一行输入,直至换行符。
然后,getline将换行符丢弃,而get()将换行符保留在输入序列里
对于string类:
方法一:getline(cin, str)。
1.利用栈的思想,利用vector,会以空格分割元素,方便。
#include <iostream>
#include<string>
using namespace std;
#include <vector>
int main()
{
string s;
vector<string> vs;
while (cin >> s)
{
vs.push_back(s); //vector中push_back函数的意思是在vector的末尾插入一个元素。
}
for (int i = vs.size() - 1; i > 0; i--)
{
cout << vs[i] << " ";
}
cout << vs[0] << endl;
return 0;
}
2.不用vector,用<stack>
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
stack<string> ss;
string s;
while(cin>>s)
{
ss.push(s);
}
while(!ss.empty())
{
cout<<ss.top();
ss.pop();
if(!ss.empty())
cout<<' ';
}
cout<<endl;
}
3.常规思路:
(1)找空格去输出。
#include <stdio.h>
#include <string.h>
int main(){
char str[1000];
char *p;
gets(str);
while (p = strrchr(str, ' ')){//判断空格的最后一次出现位置
printf("%s ", p + 1);
*p = '\0';
}
printf("%s\n", str);
return 0;
}
(2)第一个想到的思路
#include<stdio.h>
#include<string.h>
int main()
{
char s[500];
gets(s);
int len = strlen(s);
printf("%d", len);
int m = 0;
int i, j, k;
for (i = len - 1; i >= 0;i--)
{
if (s[i] == ' ')
{
k = len;
for (j = i + 1; j < k; j++)
{
printf("%c", s[j]);
}
printf(" ");
len = i;
}
if (i == 0)
{
for (j = 0; j<len; j++)
{
printf("%c", s[j]);
}
}
}
}
|
|