字符串在C++中的反向顺序
reverse order of a string in C++
我有一个 c++ 程序,它从文件中获取数据。在文件中的数据如下:
这是第 1 行
这是第2 行 这是第
3 行
这是我阅读它的方式。
ifstream file;
std::string list[max], temp;
file.open("file");
int i=0;
while ( getline (file, temp )) //while the end of file is NOT reached
{
list[i] = temp;
i++;
}
file.close();
现在我所做的是运行一个循环,如下所示
for(i=0; i<no_of_lines; i++){
temp = list[i];
}
我想要的是颠倒界限。例如,在第 1 行中,数据是 "这是第 1 行"并将 temp 中的数据更新为"1 行是这个"
我怎样才能做到这一点?
我会使用std::vector而不是固定数组和std::reverse。此解决方案还将使您的代码对任意数量的输入字符串有效。
完整代码:
typedef vector<string> StrVec;
ifstream file;
string temp;
StrVec strings;
file.open("file");
while(getline (file, temp))
{
strings.push_back(temp);
}
file.close()
printf("Before reverse:nn");
for(StrVec::iterator i = strings.begin(); i != strings.end(); ++i)
{
printf("%sn", i->c_str());
}
std::reverse(strings.begin(), strings.end());
printf("nAfter reverse:nn");
for(StrVec::iterator i = strings.begin(); i != strings.end(); ++i)
{
printf("%sn", i->c_str());
}
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 函数调用中参数的顺序重要吗
- 为什么不;名字在地图上是按顺序排列的吗
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 数到第n个楼梯的路(顺序无关紧要)
- 优先顺序:智能指针和类析构函数
- 在循环中按顺序遍历成员变量
- 独立读取-修改-写入顺序
- QML按钮点击功能执行顺序
- C++中数据类型修饰符的顺序
- 当比特(而不是字节)的顺序至关重要时的持久性
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 通过选项卡的文本设置QTabWidget顺序
- c++11评估顺序(未定义的行为)
- 如何在C++中递归地按相反顺序打印集合
- 给定顺序中的事件处理
- 具有包含其他对象的类的对象创建顺序
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 遍历顺序由 std::文件系统directory_iterator给出
- 检查 2 棵树是否具有相同的顺序