因此,我正在为讨论随机访问文件的课程做一些工作。其中一个问题(选项3)要求我们创建一个代码,该代码采用文本文件并从头到特定点(由用户提供)读取并显示其内容。在该用户提供输入后,如何设置代码以停止读取?到目前为止,这是我的代码
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <iomanip>
using namespace std;
int main() {
char filename[]="file.txt";
char content[10];
ifstream inFile;
int choice;
int option;
l1: cout << "Choose an option to decide what you want to do with the file." << endl;
cout << "Option 1: Beginning to End."<< endl;
cout << "Option 2: End to Beginning."<< endl;
cout << "Option 3: Beginning to Certain Point."<< endl;
cout << "Option 4: Certain Point to Certain Point. "<< endl;
cin >> choice;
if (choice==1){
inFile.open(filename);
if(inFile.fail())
{
cout << "file named can not be found \n";
system("pause");
exit(1);
}
inFile>>content;
while(inFile.good())
{
cout <<content<< ' ' <<endl;
inFile>>content;
}
inFile.close();
cout << "Do you want to go again? 1 for Yes and 2 for No."<< endl;
cin >> option;
if (option== 1)
{
goto l1;
}
else
{
terminate();
}
}
if (choice==2){
inFile.open(filename);
if(inFile.fail())
{
cout << "file named can not be found \n";
system("pause");
exit(1);
}
char c;
std::ifstream myFile(filename,std::ios::ate);
std::streampos size = myFile.tellg();
for(int i=1;i<=size;i++){
myFile.seekg(-i,std::ios::end);
myFile.get(c);
printf("%c",c);
}
cout << "Do you want to go again? 1 for Yes and 2 for No."<< endl;
cin >> option;
if (option== 1)
{
goto l1;
}
else
{
terminate();
}
}
if (choice==3){
inFile.open(filename);
if(inFile.fail())
{
cout << "file named can not be found \n";
system("pause");
exit(1);
}
}
}
最简单的方法是输入他们要停止读取的字符或行号,然后递增到该值。有点像
int amount_read = 0;
int amount_to_be_read;
cin >> amount_to_be_read;
inFile>>content;
while(inFile.good() && amount_read < amount_to_be_read)
{
cout <<content<< ' ' <<endl;
inFile>>content;
amount_read++;
}
inFile.close();