使用ifstream,ofstream和fstream

时间:2018-03-29 19:20:51

标签: c++ fstream ifstream ofstream

  1. 尝试将文字读入"牛肉"

  2. 稍后将文件内容编辑为用户想要的内容,并将其存储在字符串中," line"

  3. 文件永远不会显示,当我手动检查时,文本文件为空白。

  4. #include "stdafx.h"
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    
    int main()
    {
        string line = { " " };
        ofstream file1;
        file1.open("beef.txt");
        file1 << "beef" << endl;
        file1.close();
        file1.open("beef.txt");
    
        if (file1.is_open())
        {
            cout << "Enter what you would like to be contained in the file" << endl;
            cin >> line;
            ofstream file1;
            file1 << line << endl;
        }
    
        return 0;
    }
    

2 个答案:

答案 0 :(得分:1)

在此片段中:

if (file1.is_open())
{
    cout << "Enter what you would like to be contained in the file" << endl;
    cin >> line;
    ofstream file1;
    file1 << line << endl;
}

您创建了另一个ofstream对象:

ofstream file1;

这会影响您之前创建过的那个。此外,您现在正在影子的是包含指向"beef.txt"的有效文件指针的对象。使用新的内部范围file1并不指向任何文件,因此写入它不会在"beef.txt"中为您提供任何结果。

删除它以使用正确的对象:

if (file1.is_open())
{
    cout << "Enter what you would like to be contained in the file" << endl;
    cin >> line;
    file1 << line << endl;
}

答案 1 :(得分:0)

std::ofstream仅用于输出,您无法用它读取输入。

std::ifstream仅用于输入,您无法用它写输出。

所以,你需要

  • 使用单独的std::ofstreamstd::ifstream变量:

    int main()
    {
        ofstream out_file;
        ifstream in_file;
        string line;
    
        out_file.open("beef.txt", ios_base::trunc);
        if (out_file.is_open())
        {
            out_file << "beef" << endl;
            out_file.close();
        }
    
        in_file.open("beef.txt");
        if (in_file.is_open())
        {
            getline(in_file, line);
            in_file.close();
    
            cout << "File contains:" << endl;
            cout << line << endl;
        }
    
        cout << "Enter what you would like to be contained in the file" << endl;
        getline(cin, line);
    
        out_file.open("beef.txt", ios_base::trunc);
        if (out_file.is_open())
        {
            out_file << line << endl;
            out_file.close();
        } 
    
        in_file.open("beef.txt");
        if (in_file.is_open())
        {
            getline(in_file, line);
            in_file.close();
    
            cout << "File now contains:" << endl;
            cout << line << endl;
        }
    
        return 0;
    }
    
  • 使用单个std::fstream变量,可以用于输出和输入,具体取决于在调用{{1时是否指定in和/或out标志}}:

    open()