C++如何将变量用于 ifstream
C++ how do i use a variable for ifstream
void searchString(const string selection,const string filename)
{
ifstream myfile;
string sline;
string sdata;
myfile.open(filename);
while(!myfile.eof())
{
getline(myfile,sline);
sdata = sdata + sline;
}
如何使用字符串文件名作为myfile.open(文件名(
最初我使用的是 file.txt,但是如果我使用由函数传入的变量,例如字符串文件名,它会给我一个错误
myfile.open("file.txt");
错误消息如下:
main.cpp:203:25: error: no matching function for call to ‘std::basic_ifstream<char>::open(const string&)’
main.cpp:203:25: note: candidate is:
/usr/include/c++/4.6/fstream:531:7: note: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char, _Traits = std::char_traits<char>, std::ios_base::openmode = std::_Ios_Openmode]
/usr/include/c++/4.6/fstream:531:7: note: no known conversion for argument 1 from ‘const string {aka const std::basic_string<char>}’ to ‘const char*’
make: *** [main.o] Error 1
std::ifstream::open
的构造函数(针对您正在使用的特定C++标准(不允许std::string
参数,因此您必须使用:
myfile.open(filename.c_str());
构造函数需要可以使用其 c_str()
成员函数从 std::string
对象获取的类型 const char *
。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 用于访问容器<T>数据成员的正确 API
- ifstream什么都没读
- 重载操作程序时出错>>用于类中的字符串 memebr
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- C++中的cin.ignore()函数不适用于整个流
- 没有用于初始化C++中的变量模板的匹配构造函数
- 用于C++中带有数组和指针的循环
- 为什么它不适用于Visual 2019的原因
- 使用在用于SFINAE的void_t中具有参数的方法
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息
- ifstream 没有用于初始化的匹配构造函数
- 没有用于初始化"ifStream"的匹配构造函数
- 用于中断哈希字符串的 ifstream
- ifstream/ofstream真的用于序列化吗
- std::getline 用于 ifstream,使用参数字符串或 char *
- C++如何将变量用于 ifstream
- Ifstream 不适用于 OpenGL/freeglut
- 哪个操作符重载被用于ifstream对象求值为布尔值