尝试将文字读入"牛肉"
稍后将文件内容编辑为用户想要的内容,并将其存储在字符串中," line"
文件永远不会显示,当我手动检查时,文本文件为空白。
#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;
}
答案 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::ofstream
和std::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()