简体   繁体   中英

Path String Concatenation Question

Please see my code below.

ifstream myLibFile ("libs//%s" , line); // Compile failed here ???

I want to combine the path string and open the related file again.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("libs//Config.txt");  
  // There are several file names listed in the COnfig.txt file line by line.
  if (myfile.is_open())
  {
    while (! myfile.eof() )
    {
  getline (myfile,line);
  cout << line << endl;
  // Read details lib files based on the each line file name.
  string libFileLine;
  ifstream myLibFile ("libs//%s" , line);  // Compile failed here ???
  if (myLibFile.is_open())
  {
   while (! myLibFile.eof() )
   {
    cout<< "success\n";
   }
   myLibFile.close();
  }


    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

Assume my [Config.txt] include the content below. And all the *.txt files located in libs folder.

file1.txt
file2.txt
file3.txt

The ifstream constructor does not work that way. Its first parameter is a C string to the file you want to open. Its second parameter is an optional set of mode flags.

If you want to concatenate the two strings, just concatenate the two strings:

std::string myLibFileName = "libs/" + line;
ifstream myLibFile(myLibFileName.c_str());

// Or, in one line:
ifstream myLibFile(("libs/" + line).c_str());

(the call to c_str() is required because the ifstream constructor takes a const char* , not a std::string )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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