如何读取和写入C ++中的文本文件? [英] How to read and write to a text file in C++?
问题描述
#include< iostream>
#include< fstream>
using namespace std;
string usreq,usr,yn,usrenter;
int start()
{
cout<< Welcome ...
int main()
{
cout< 这是你第一次使用TEST< endl;
cin>> yn;
if(yn ==y)
{
ofstream iusrfile;
ofstream ousrfile;
iusrfile.open(usrfile.txt,w);
iusrfile>> ;
cout<< iusrfile;
iusrfile.close();
cout<< 请输入您的用户名。\\\
;
cin>>用户
if(usrenter == usr)
{
start();
}
}
else
{
cout< 不是注册的用户名。
}
return 0;
}
需要:
#include< iostream>
#include< fstream>
声明输入文件流:
ifstream in(in.txt);
声明输出文件流:
ofstream out(out.txt);
如果要对文件名使用变量而不是硬编码, p>
string file_name =my_file.txt;
ifstream in2(file_name.c_str());
从文件读入变量(假设文件中有2个int变量):
int num1,num2;
在>> num1>> num2;
或从文件中读取一行时间:
string行;
while(getline(in,line)){
//使用行
执行某些操作
将变量写回文件:
out< num1<< num2;
关闭文件:
in.close();
out.close();
Hey everyone, I have just started to learn C++ and I wanted to know how to read and write to a text file. I have seen many examples but they have all been hard to understand/follow and they have all varied. I was hoping that someone here could help. I am a total beginner so I need clear instructions. Here is an example of what i'm trying to do:
#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;
}
Header files needed:
#include <iostream>
#include <fstream>
declare input file stream:
ifstream in("in.txt");
declare output file stream:
ofstream out("out.txt");
if you want to use variable for a file name, instead of hardcoding it, use this:
string file_name = "my_file.txt";
ifstream in2(file_name.c_str());
reading from file into variables (assume file has 2 int variables in):
int num1,num2;
in >> num1 >> num2;
or, reading a line a time from file:
string line;
while(getline(in,line)){
//do something with the line
}
write variables back to the file:
out << num1 << num2;
close the files:
in.close();
out.close();
这篇关于如何读取和写入C ++中的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!