习惯了其他语言的字符串操作,对C++的字符串操作确有不适之处,特别是在find_last_of这个函数上,尝试了很多次都找不到错误的原因。比如这段代码:
string in;
cin >> in;
string::size_type at = in.find_last_of(".dat");
string fn = "default.dat";
if (at!=npos) {
fn = in;
string s = in.substr(0, in.length() - at);
cout << "输入文件为:" << s << endl;
}
else {
cout << "输入文件不正确" << endl;
}
无论我们输入什么样的.dat文件名,s的结果始终为文件名的第一个字符。特别是当我们输入为汉字的文件名时,s的输出结果肯定是一个乱码。
按照其他语言的套路,尝试了若干遍,最终还是在find_last_of函数的说明中找到了原因。C++中find_last_of函数在in这个字符串中,找到".dat"时,返回的是最后一个字符(这里也就是t)的位置,不是需要查找的关键字的第一个字符(这里是.)的位置!
因此,以上代码对应部分需要修改为:
string s = in.substr(0, at - string(".dat").length() + 1);