如何读取和写入C ++中的文本文件? [英] How to read and write to a text file in C++?

查看:345
本文介绍了如何读取和写入C ++中的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿大家,我刚刚开始学习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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆