J'écris un programme qui lit à partir de deux fichiers ("joke.text" et "punchline.txt") il y a "garbage" dans le fichier punchline et je ne sais pas comment lis juste la ligne que je veux. S'il vous plaît aider. De plus, je suis en utilisant Visual Studioscomment lire à partir du milieu du fichier texte
ce que j'ai:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream jokeFile;
string data;
char input;
cout << "opening the file... \n";
jokeFile.open("joke.txt", ios::in);
if (jokeFile.is_open())
{
getline(jokeFile, data);
while (jokeFile)
{
cout << data <<endl;
getline(jokeFile, data);
}
jokeFile.close();
}
else
{
cout << "ERROR: could not open that file\n";
}
cout << "would like you see the punchline? (Y/N) \n";
cin >> input;
/* if (input == 'N' || 'n')
{
cout << "Ok, keep guessing\n";
}*/
if (input == 'Y' || 'y')
{
jokeFile.open("punchline.txt", ios::in);
if (jokeFile.is_open())
{
//getline(jokeFile, data, '\n');
while (jokeFile)
{
cout << data;
getline(jokeFile, data, '\n');
}
jokeFile.close();
}
else
{
cout << "ERROR: could not open the file\n";
}
}
/*{
cout << "invalid response, try again\n";
}*/
system("pause");
return 0;
}
et est ici la sortie:
opening the file...
Two men who work together in a facory were talking.
"I know how to get some time off," said one.
"How are you going to do that?" asked the other.
"Watch," he said, and climbed a ladder to the ceiling.
The foreman asked what he was doing up there,
and the man replied. "I'm a lightbulb."
"I think you need some time off," the foreman
said, and the first man walked out of the
factory. After a moment, the second man followed
him. "Where do you think you're going?"
the foreman shouted.
would like you see the punchline? (Y/N)
y
asdasdasdasdasdfdssdfdsaasdfdssfddsfdsasdsad"I can't work in the dark, " he said.
Comment le programme sait-il quelle ligne il veut? (Ou comment le savoir?) – immibis
Si vous savez exactement quelle ligne vous voulez lire, vous pouvez appeler 'fseek()', ce qui changera le pointeur de fichier à la ligne que vous voulez. Après cela, vous pouvez appeler 'getline()' – Elias