字符串在C++中的反向顺序

reverse order of a string in C++

本文关键字:顺序 C++ 字符串      更新时间:2023-10-16

我有一个 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());
}