【问题标题】:C++ issue with ifstream() taking filename from string variableifstream() 从字符串变量中获取文件名的 C++ 问题
【发布时间】:2019-04-06 16:14:45
【问题描述】:

我遇到了这个简单但烦人的问题。

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文件的内容

Jan.csv

二月.csv

我尝试使用

将字符串作为 c 字符串传递

ifstream dataFile(filePath.c_str());

仍然无法找到该文件。

【问题讨论】:

  • 如果您在运行时检查文件名,它是否包含正确的名称(没有无效字符)?
  • 很可能有尾随换行符。
  • .txt 文件中的行尾是否适合您的平台?
  • 谢谢大家。文件名以“\r”结尾。找到问题了。

标签: c++ string ifstream


【解决方案1】:

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

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

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

1) 通过单击要检查的行的左侧来设置断点

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

3) 通过调试器控制台检查

【讨论】:

  • 你知道'\r' 来自哪里吗? (Windows \r\n 换行符。)你知道如何解决'\r' 卡在字符串末尾的问题吗? (在 Windows 上以 text 模式打开 text 文件。)
猜你喜欢
  • 1970-01-01
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
相关资源
最近更新 更多