C++ ifstream :注意事项,ifstream 参数不能是 string 型

C++ 中 ifstream 是一种常用的打开文件的方式,使用方式:

void Void_data_read ()
{
    ifstream ifstream_myfile ( "E:\\Python_Work\\Lithology\\Lithology.txt" );
    if ( !ifstream_myfile.is_open() ) {
        cout << "未成功打开文件!" << endl;
        exit;
    }
    else {
        string string_currentLine;
        while ( getline( ifstream_myfile, string_currentLine ) ) {
            cout << string_currentLine << endl;
        }
    }
    return;
}

在第三行语句的括号中需要给出文件路径。常用方式:

  1. 直接在括号中写出文件路径并用双引号括起来,注意文件夹之间的反斜杠要写两个
  2. 在函数最前面 #define 路径值,如下:
#define path "E:\\Python_Work\\Lithology\\Lithology.txt"
void Void_data_read ()
{
    ifstream ifstream_myfile ( path );
    if ( !ifstream_myfile.is_open() ) {
        cout << "未成功打开文件!" << endl;
        exit;
    }
    else {
        string string_currentLine;
        while ( getline( ifstream_myfile, string_currentLine ) ) {
            cout << string_currentLine << endl;
        }
    }
    return;
}

这种方式可以在函数中节省代码量,更易于修改路径。

  1. 将文件路径名称写入 char 型字符数组中,并将字符数组作为参数传递
void Void_data_read ( char filePath[] )
{
    ifstream ifstream_myfile ( filePath );
    if ( !ifstream_myfile.is_open() ) {
        cout << "未成功打开文件!" << endl;
        exit;
    }
    else {
        string string_currentLine;
        while ( getline( ifstream_myfile, string_currentLine ) ) {
            cout << string_currentLine << endl;
        }
    }
    return;
}

int main()
{
	char filePath[80] = path;
	Void_data_read( filePath );
	return 0;
}

如果采用 string 类型作为参数传递文件路径则会报错,如下:

void Void_data_read ( string filePath )
{
    ifstream ifstream_myfile ( filePath );
    if ( !ifstream_myfile.is_open() ) {
        cout << "未成功打开文件!" << endl;
        exit;
    }
    else {
        string string_currentLine;
        while ( getline( ifstream_myfile, string_currentLine ) ) {
            cout << string_currentLine << endl;
        }
    }
    return;
}

int main()
{
	string str_filePath = path;
	Void_data_read( str_filePath );
	return 0;
}

这种方式会报错:
[Error] no matching function for call to ‘std::basic_ifstream::basic_ifstream(std::string&)’

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值