根据用户输入打开文件c ++ [英] opening a file based on user input c++
问题描述
我正在尝试制作一个程序,该程序将根据用户输入打开文件.这是我的代码:
I am trying to make a program that would open a file based on the users input. Here`s my code:
#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;
}
但是当我编译它时,它给了我这个错误:
But when I compile it, it gives me this error:
[Error] no match for 'operator<<' (operand types are 'std::ifstream {aka std::basic_ifstream<char>}' and 'const char [7]')
有人知道如何解决这个问题吗?谢谢...
Does anyone know how to solve this? Thank you...
推荐答案
您的代码有几个问题.首先,如果要写入文件,请使用 ofstream
. ifstream
仅用于读取文件.
Your code has several problems. First of all, if you want to write in a file, use ofstream
. ifstream
is only for reading files.
第二,open方法使用一个 char []
,而不是一个 string
.在C ++中存储字符串的常用方法是使用 string
,但是它们也可以存储在 char
s数组中.要将 string
转换为 char []
,请使用 c_str()
方法:
Second of all, the open method takes a char[]
, not a string
. The usual way to store strings in C++ is by using string
, but they can also be stored in arrays of char
s. To convert a string
to a char[]
, use the c_str()
method:
fileC.open(filename.c_str());
close
方法是一个方法,而不是属性,因此需要括号: fileC.close()
.
The close
method is a method, not an attribute, so you need parentheses: 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;
}
这篇关于根据用户输入打开文件c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!