首页 > 解决方案 > 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());

仍然无法找到该文件。

标签: c++stringifstream

解决方案


发现问题。文件名以“\r”结尾。

对于像我这样使用代码块的 C++ 新手来说——

您可以在运行时通过设置断点检查文件名并从调试器控制台检查。

1)通过单击要检查的行的左侧来设置断点 在此处输入图像描述

2)通过单击顶部“红色一号”的调试按钮运行调试器。

3) 通过调试器控制台检查 在此处输入图像描述

在此处输入图像描述


推荐阅读