基于用户输入c++打开一个文件
opening a file based on user input c++
我正在尝试制作一个程序,根据用户的输入打开一个文件。这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string filename;
ifstream fileC;
cout<<"which file do you want to open?";
cin>>filename;
fileC.open(filename);
fileC<<"lalala";
fileC.close;
return 0;
}
但当我编译它时,它会给我一个错误:
[Error] no match for 'operator<<' (operand types are 'std::ifstream {aka std::basic_ifstream<char>}' and 'const char [7]')
有人知道怎么解决这个问题吗?非常感谢。
您的代码有几个问题。首先,如果要在文件中进行写入,请使用ofstream
。ifstream
仅用于读取文件。
其次,open方法采用char[]
,而不是string
。在C++中存储字符串的常用方法是使用string
,但它们也可以存储在char
s的数组中。要将string
转换为char[]
,请使用c_str()
方法:
fileC.open(filename.c_str());
close
方法是一个方法,而不是属性,因此需要括号:fileC.close()
。
因此,正确的代码如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string filename;
ofstream fileC;
cout << "which file do you want to open?";
cin >> filename;
fileC.open(filename.c_str());
fileC << "lalala";
fileC.close();
return 0;
}
您不能写入ifstream
,因为它用于输入。您想要写入ofstream
,它是输出文件流。
cout << "which file do you want to open?";
cin >> filename;
ofstream fileC(filename.c_str());
fileC << "lalala";
fileC.close();
相关文章:
- 挂起和取消挂起一个文件DLL
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- C++试图读取一个文件并输出到另一个文本文件
- 如何从另一个文件继承私有成员变量和公共函数
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 如何将class.cpp和class.hpp编译为一个.o文件
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 如何从整个磁盘中排除要装载的一个文件
- 如何将模板和非模板函数放在一个文件中
- 如何在安卓工作室中将c ++头文件从一个文件夹导入到另一个文件夹?
- 使用 scope 运算符 (::) 引用另一个文件中的类
- JNI,使用两个 .so 文件时出错,其中一个文件需要另一个文件
- 为什么我不能从同一目录中的另一个文件中 #include 我的类?
- 在 c++ 中打开文件、删除标点符号并追加到另一个文件中
- C++ 如何将两个 makefile 对象目标规则(位于另一个文件夹中)合并到一个目标/规则中?
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?
- c++ 提升如果 .extension() == " "这意味着这个文件是一个文件夹?
- 是否可以在 c++ 中创建一个文件并为其提供属性以将其隐藏?(在 Ubuntu 上)
- 我需要编写一个程序来读取一个文件,该文件将输出所有唯一的整数,如果已经看到整数,它将被关闭
- 如何在标准c ++中流式传输/读取二进制文件的中间部分并写入另一个文件?