c++ - ifstream() 从字符串变量中获取文件名的 C++ 问题
问题描述
我遇到了这个简单但烦人的问题。
ifstream dataFile(fileName) 如果 fileName 是硬编码的或通过字符串变量分配的,则可以正常工作,但是当从参数提供时,它无法找到文件。
我有以下代码 -
//This function will get filenames from a .txt file
//Then call getDataFromFile() with filename as argument
void getFileNames(string dataFileName){
string line;
ifstream dataFile(dataFileName);
if(!dataFile){
cout << "Error! No such file found! Ending Program." <<
endl;
exit(0);
}
while(getline(dataFile,line)){
if(!line.empty()){
getDataFromFile(line);
}
}
}
//**Issue is inside this function**
void getDataFromFile(string fileName){
//Files are under "data/" path -
//To access Jan.csv - "data/Jan.csv"
string filePath = "data/Jan.csv"; //Works
string filePath = "data/"+fileName; //Not working - Unable to find file
ifstream dataFile(filePath);
//...Rest of code
}
以下是 .txt 文件的内容
一月.csv
二月.csv
我尝试使用将字符串作为 c 字符串传递
ifstream dataFile(filePath.c_str());
仍然无法找到该文件。
解决方案
推荐阅读
- python - python:RecursionError:调用将数据帧传递给类方法的Python对象时超出了最大递归深度
- node.js - 在 node.js 中上传多个图像时出错
- c# - 不要在 BindingSource C# 中对历史列进行排序
- outlook - Outlook 日历 API 支持哪些 Outlook 产品?
- react-native - AppRegistry 在 React-Native 中的使用?有例子吗?
- vue.js - Vuejs将动态数据从父组件传递给子组件
- python - 为什么python多处理初始化相同的值?
- google-compute-engine - 在 Google Compute Engine 中创建暂存 VM
- gtsummary - 按组拆分汇总表时如何标记列并保留组大小?
- mysql - 使用 NODEJS -LAMBDA 将 EPOCH 时间转换为 MYSQL TIMESTAMP