-5

I have a c++ program where it take data from a file. In file data is as follows:

this is line 1

this is line 2

this is line 3

Here's how I read it.

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();

Now what I do is run a loop as follows

for(i=0; i<no_of_lines; i++){
    temp = list[i];


}

What i want is to reverse the line. For example in line 1 data is 'this is line 1' and update data in temp as '1 line is this'

How can I achieve that?

code maniac
  • 37
  • 1
  • 5

1 Answers1

0

I would use std::vector instead of fixed array and std::reverse. This solution will also make your code valid for any number of input strings.

Complete code:

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:\n\n");
for(StrVec::iterator i = strings.begin(); i != strings.end(); ++i)
{
    printf("%s\n", i->c_str());
}

std::reverse(strings.begin(), strings.end());

printf("\nAfter reverse:\n\n");
for(StrVec::iterator i = strings.begin(); i != strings.end(); ++i)
{
    printf("%s\n", i->c_str());
}
Mateusz Grzejek
  • 11,698
  • 3
  • 32
  • 49