2013-12-10 54 views
0

我试图打开一个.dat文件以用作我的程序的输入。该任务说我需要将我输入的文件名称转换为c-string数据类型,以便通过.open(“”)命令读取它。我的程序编译完成,但我确信当我尝试转换文件名时,我做错了什么。我曾四处寻找有类似问题的人,但我没有运气,所以你可以给我的任何建议将非常感激!将文件的名称转换为c字符串

这里是我尝试打开文件的功能,以及我尝试转换文件名的其他功能。

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 file\n"; 
     exit (1); 
    } 
} 
+4

是什么让你觉得你做错了什么? – 0x499602D2

+0

当你运行程序时会发生什么?如果编译器没有发出抱怨,您的转换必须给出一些合理的结果... – abiessu

+0

当我输入为作业下载的.dat文件的名称时,程序输出“Error opening file”。 – user3063730

回答

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()); 

备注:数组中的元素索引为0SIZE - 1所以当你宣布:

float pay[SIZE]; 

然后当你这样做:

pay[SIZE] = calcPay(rate, sum); 

您正在访问的内存 “通行证” 的最后一个元素,这将导致未定义行为

+0

我正在建议c_str()我自己 – portforwardpodcast

+0

'fp.is_open()'不正确,因为它不检查失败位。 'if(!fp)'是正确的习惯用语。另请参见:[basic_ios的参考资料](http://en.cppreference.com/w/cpp/io/basic_ios/operator!)。 – SoapBox

+0

@SoapBox:够公平的,我不应该写'if(!fp)'不正确。但是,如果文件不存在,'is_open()'可以做得很好。 – LihO