简体   繁体   English

ifstream() 从字符串变量中获取文件名的 C++ 问题

[英]C++ issue with ifstream() taking filename from string variable

I am having this simple yet annoying issue.我遇到了这个简单而烦人的问题。

ifstream dataFile(fileName) works fine if fileName is hard-coded or assign via a string variable however when supplied from an argument, it is unable to find the file. ifstream dataFile(fileName) 如果 fileName 是硬编码的或通过字符串变量分配的,则工作正常,但是当从参数提供时,它无法找到文件。

I have the following code -我有以下代码 -

//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
}

Below is the content of .txt file下面是 .txt 文件的内容

Jan.csv一月文件

Feb.csv 2月.csv

I have tried to pass the string as c string using我试图将字符串作为 c 字符串传递使用

ifstream dataFile(filePath.c_str()); ifstream dataFile(filePath.c_str());

and still unable to find the file.并且仍然无法找到该文件。

Found the issue.发现问题。 Filename is ending with "\\r".文件名以“\\r”结尾。

For c++ newbies like me who are using codeblock -对于像我这样使用代码块的 C++ 新手 -

You can check filename during run-time by setting breakpoints and check from the Debugger console.您可以在运行时通过设置断点来检查文件名,并从调试器控制台进行检查。

1) Set breakpoints by clicking at the left side of the line that you want to check 1) 通过单击要检查的行的左侧来设置断点在此处输入图片说明

2) Run the debugger by clicking the debug button at the top "the red color one". 2)通过单击顶部“红色之一”的调试按钮运行调试器。

3) Check via the debugger console 3)通过调试器控制台检查在此处输入图片说明

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM