将文件名转换为c字符串
Converting the name of a file into a c-string
我正试图打开一个.dat文件作为程序的输入。作业中说,我需要将为文件名输入的名称转换为c-string数据类型,以便可以通过.open(")命令读取。我的程序正在编译,但当我尝试转换文件名时,我确信我做错了什么。我四处寻找有类似问题的人,但我运气不好,所以如果你能给我任何建议,我将不胜感激!
这是我尝试打开文件的函数,以及我尝试转换文件名的另一个函数。
int main()
{
ifstream fp;
string name[SIZE], filename;
int counter, idx = 0;
float rate[SIZE], sum[SIZE], gross[SIZE], with[SIZE], pay[SIZE], net[SIZE], hours[SIZE];
getfile(fp, filename);
readFile(fp, name, rate, hours);
pay[SIZE] = calcPay(rate, sum);
gross[SIZE] = calcGross(pay);
with[SIZE] = calcAmount(gross);
net[SIZE] = calcNet(gross, with);
output(name, rate, sum, with, gross, net, pay, SIZE);
return 0;
}
//Convert filename into C-string
string convert(ifstream &fp, string filename)
{
fp.open(filename.c_str());
return filename;
}
//Get file name from user.
void getfile(ifstream &fp, string filename)
{
cout <<" Enter the name of the file: ";
cin>>filename;
convert(fp, filename);
fp.open("filename");
if (!fp)
{
cout<<"Error opening filen";
exit (1);
}
}
cout <<" Enter the name of the file: ";
cin>>filename;
convert(fp, filename);
fp.open("filename");
可能是(在目前支持C++11的情况下):
cout << " Enter the name of the file: ";
cin >> filename;
fp.open(filename);
或(在C++03中):
cout << " Enter the name of the file: ";
cin >> filename;
fp.open(filename.c_str());
旁注:数组中的元素从0
索引到SIZE - 1
,因此当您声明:时
float pay[SIZE];
然后当你这样做时:
pay[SIZE] = calcPay(rate, sum);
您正在访问内存"传递"最后一个元素,这将导致未定义的行为。
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将这个std::字符串转换为std::基本字符串
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 如何在C++中将十六进制字符串转换为文本数据
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何从字符串转换为双精度*
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- 如何将整数字符串转换为整数的二维向量?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 将文件复制到自定义位置,存在字符串转换问题
- 将ANSI C字符串转换为UNICODE
- 如何将节点 V8 字符串转换为 C++ 字符串
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将字符串转换为无符号字符数组/字节数组