输入字符串输出字符串的倒序,如输入hellow, world,输出world hellow,运用vector和getline
时间: 2023-06-09 11:08:31 浏览: 49
好的,您的第一个问题是输入字符串输出字符串的倒序,如输入hellow, world,输出world hellow,运用vector和getline。以下是代码:
```c++
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> vec;
std::string input;
std::getline(std::cin, input);
std::string temp = "";
// 将输入字符串按空格截取并存入vector中
for (int i = 0; i < input.length(); ++i) {
if (input[i] == ' ') {
vec.push_back(temp);
temp = "";
} else {
temp += input[i];
}
}
vec.push_back(temp);
// 倒序输出vector中的字符串
for (int i = vec.size() - 1; i >= 0; --i) {
std::cout << vec[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
使用 `getline` 函数获取输入字符串,然后将其按照空格进行分割,存储到 `vector` 中。之后,从 `vector` 的最后一个元素依次输出每个字符串即可得到倒序字符串的效果。