Need help (File) C++
Oct 28, 2015 at 2:13pm UTC
Hello, i make a code in c++ for read files.
This code read of last line until first line, but i want know if have how improve this code.
My file:
Sum: 3 4 5 6 = 18
Sum: 2 3 4 5 = 32
Sum: 3 4 5 6 = 50
Sum: 1 2 3 4 = 60
Sum: 5 6 7 = 78
Sum: 3 3 5 6 = 17
Sum: 2 2 = 4
Sum: 1 1 = 2
Sum: 68 1 = 69
Sum: 11 11 = 22
Sum: 7 7 = 14
my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int cont;
string operacao;
for (int i = 0; i < 10; i++){
cont = 0;
ifstream input("historico.txt" );
while (!input.eof()){
getline (input,operacao);
if (cont == 10 - i){
cout << operacao << " " ;
}
cont++;
}
cout << endl;
}
return 0;
}
Last edited on Oct 28, 2015 at 2:14pm UTC
Oct 28, 2015 at 3:58pm UTC
it would be more efficient to read the file one time only. consider that to be a data cache. then you can work backwards or forwards at the same speed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
{
string operacao;
vector<string> operations;
// cache the file contents
ifstream input("historico.txt" );
while (!input.eof())
{
getline (input,operacao);
operations.push_back(operacao);
}
input.close();
// output the list in reverse order
for (auto it = operations.rbegin(); it != operations.rend(); ++it)
{
cout << *it << endl;
}
return 0;
}
Oct 28, 2015 at 7:53pm UTC
But i can't use vector!
Oct 29, 2015 at 9:35am UTC
Does that mean you are not permitted or you don't understand how vectors work
If you aren't permitted to use STL containers then perhaps design and implement your own linked list?
Topic archived. No new replies allowed.