大家好,我刚刚开始学习C++,我想知道如何读写文本文件。我见过很多例子,但它们都很难理解/遵循,而且它们都是多种多样的。我希望这里有人能帮上忙。我是一个完全的初学者,所以我需要明确的指示。下面是我想要做的一个例子:
#include <iostream>
#include <fstream>
using namespace std;
string usreq, usr, yn, usrenter;
int start ()
{
cout << "Welcome..."
int main ()
{
cout << "Is this your first time using TEST" << endl;
cin >> yn;
if (yn == "y")
{
ofstream iusrfile;
ofstream ousrfile;
iusrfile.open("usrfile.txt", "w");
iusrfile >> usr;
cout << iusrfile;
iusrfile.close();
cout << "Please type your Username. \n";
cin >> usrenter;
if (usrenter == usr)
{
start ();
}
}
else
{
cout << "THAT IS NOT A REGISTERED USERNAME.";
}
return 0;
}
发布于 2011-05-19 07:17:36
所需的头文件:
#include <iostream>
#include <fstream>
声明输入文件流:
ifstream in("in.txt");
声明输出文件流:
ofstream out("out.txt");
如果您希望使用变量作为文件名,而不是对其进行硬编码,请使用以下命令:
string file_name = "my_file.txt";
ifstream in2(file_name.c_str());
从文件读取到变量(假设文件中有两个整型变量):
int num1,num2;
in >> num1 >> num2;
或者,从文件中一次读取一行:
string line;
while(getline(in,line)){
//do something with the line
}
将变量写回文件:
out << num1 << num2;
关闭文件:
in.close();
out.close();
发布于 2011-05-19 07:19:57
文件IO的默认c++机制称为流。流可以有三种风格:输入、输出和输入输出。输入流的作用类似于数据源。要从输入流中读取数据,可以使用>>
运算符:
istream >> my_variable; //This code will read a value from stream into your variable.
对于不同的类型,Operator >>
的作用也不同。如果在上面的例子中my_variable
是一个整数,那么将从流中读取一个数字,如果my_variable
是一个字符串,那么将读取一个单词,依此类推。您可以通过编写istream >> a >> b >> c;
从流中读取多个值,其中a,b和c将是您的变量。
输出流的作用类似于接收器,您可以将数据写入其中。要将数据写入流,请使用<<
运算符。
ostream << my_variable; //This code will write a value from your variable into stream.
与输入流一样,您可以通过编写以下代码向流中写入几个值:
ostream << a << b << c;
显然,输入输出流可以同时充当两者。
在您的代码示例中,使用了cout
和cin
流对象。cout
代表控制台输出,cin代表console-input
。这些是用于与默认控制台交互的预定义流。
要与文件交互,您需要使用ifstream
和ofstream
类型。与cin
和cout
类似,ifstream
代表input-file-stream
,ofstream
代表output-file-stream
。
您的代码可能如下所示:
#include <iostream>
#include <fstream>
using namespace std;
int start()
{
cout << "Welcome...";
// do fancy stuff
return 0;
}
int main ()
{
string usreq, usr, yn, usrenter;
cout << "Is this your first time using TEST" << endl;
cin >> yn;
if (yn == "y")
{
ifstream iusrfile;
ofstream ousrfile;
iusrfile.open("usrfile.txt");
iusrfile >> usr;
cout << iusrfile; // I'm not sure what are you trying to do here, perhaps print iusrfile contents?
iusrfile.close();
cout << "Please type your Username. \n";
cin >> usrenter;
if (usrenter == usr)
{
start ();
}
}
else
{
cout << "THAT IS NOT A REGISTERED USERNAME.";
}
return 0;
}
要进一步阅读,您可能需要查看c++ I/O reference
发布于 2011-05-19 06:47:54
为了读取,你应该创建一个ofstream的实例,而不是ofstream的实例。
ifstream iusrfile;
您应该在读取模式下打开文件。
iusrfile.open("usrfile.txt", ifstream::in);
同样,这句话是不正确的。
cout<<iusrfile;
如果您正在尝试打印从文件中读取的数据,则应执行以下操作:
cout<<usr;
您可以阅读更多关于ifstream及其API here的内容。
https://stackoverflow.com/questions/6051865
复制相似问题