本文是我之前撰写的有关如何创建文本文件的文章的第二部分。
在本文中,您将学习如何读取我们创建的文本文件,我将教您如何将该代码与我们创建的代码一起使用,但是如果您想将其放入另一个项目或源文件中并分别进行编译那也会起作用。
现在开始代码:您应该已经在源文件中包含此文件:
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ofstream Myfile;
Myfile.open ("test.txt");
Myfile << "This is a test.";
Myfile.close();
return 0;
}
在本教程中,我确实使用大写字母将myfile更改为Myfile。
1->在“ Myfile.close();”下留一个空格 使代码看起来更整洁并放入:
ifstream myfile;
ifstream提供了一个接口,可以从文件中读取数据作为输入流。
2->在该目录下打开您的文件。
myfile.open("test.txt");
3->现在创建一个字符,我们将其称为“输出”。
char output[100];
4->现在创建一个“ if”语句。
if (myfile.is_open()) {
}
5->在'if'语句中,使用char输出文本文件的内容。
while (!myfile.eof()) {
myfile >> output;
cout<<output;
}
6->现在,在if语句下,关闭文本文件。
myfile.close();
您的代码(如果您也做了第一篇文章)应该如下所示:
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ofstream Myfile;
Myfile.open ("test.txt");
Myfile << "Hello";
Myfile.close();
ifstream myfile;
myfile.open("test.txt");
char output[100];
if (myfile.is_open()) {
while (!myfile.eof()) {
myfile >> output;
cout<<output;
}
}
myfile.close();
getchar();
getchar();
return 0;
}
如果我错过任何事情,请发表评论并告诉我。
如果您有任何问题或想知道什么,请随时发邮件给我或发送电子邮件至:<已删除电子邮件地址>
From: https://bytes.com/topic/c/insights/927167-how-read-text-file-c