我正在編寫一個從兩個文件(「joke.text」和「punchline.txt」)中讀取的程序,在punchline文件中有「垃圾」,我無法弄清楚如何只讀我想要的行。請幫忙。另外,我使用視覺工作室如何從文本文件的中間讀取
這是我有:
#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;
}
,這裏是輸出:
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.
程序如何知道它想要哪一行? (或者應該怎麼知道?) – immibis
如果你確切地知道你想讀的是哪行,你可以調用'fseek()',它將把文件指針改爲你想要的行。之後,你可以調用'getline()' – Elias