我需要在ifstream加载的文件中导航。确切地说,我需要保存我之前的位置,以便在阅读几行后能够返回到这个确切的位置。 我尝试过类似的东西:
ifstream baseINTING("base.txt");
streampos position1, position2, position3;
position1 = baseINTING.tellg();
后来我读了几行:
getline(baseINTING, buffer2);
试图回去:
baseINTING.seekg(position1);
但它不起作用。有人能帮助我吗?我真的需要那个结局。
这是完整的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <direct.h>
#include <cstdlib>
using namespace std;
void anyNextOne(ifstream* newFile)
{
ifstream baseINTING("base.txt");
int j;
string buffer2;
streampos position1;
getline(baseINTING, buffer2);
getline(baseINTING, buffer2);
position1 = baseINTING.tellg();
for(j=0; j<5; j++)
{
getline(baseINTING, buffer2);
cout<<buffer2<<endl;
cout<<position1<<endl;
baseINTING.seekg(position1);
}
}
int main()
{
ifstream one("one.txt");
anyNextOne(&one);
return 0;
}
示例输出:
配料(4人份)
40
(4人)
40
(4人)
40
(...)
&#34; base.txt&#34;文件内容:
Easy Pizza Recipe
Dough:
Ingredients (for 4 people)
• 1 cup of warm water
• 3 1/2 cups of flour
• 2 tablespoons of olive oil
• 2 teaspoons of honey
• 1 teaspoon of salt
• 1 teaspoon of yeast
Method:
1. Put warm water into a bowl. Add salt and honey and mix with a spoon. Add yeast, mix and let it sit for about 10 minutes.
2. add flour and olive oil and start mixing.
3. Let it sit for about another hour.
4. Put on some tomato sauce.
5. Put on your pizza topping (some green peppers, mushrooms, ketchup, cheese, sausage, salt and pepper)
6. Bake the pizza in you oven at 200 C for about 20 to 25 minutes.
答案 0 :(得分:0)
#include <iostream>
#include <fstream>
#include <string>
#include <direct.h>
#include <cstdlib>
using namespace std;
void anyNextOne(ifstream* newFile)
{
ifstream baseINTING("base.txt");
int j;
string buffer2;
streampos position1;
getline(baseINTING, buffer2);
getline(baseINTING, buffer2);
position1 = baseINTING.tellg();
for(j=0; j<5; j++)
{
getline(baseINTING, buffer2);
cout<<buffer2<<endl;
cout<<position1<<endl;
baseINTING.seekg(position1);
}
}
int main()
{
ifstream one("one.txt");
anyNextOne(&one);
return 0;
}