hi i have a function that opens a file and store the data into a matrix

void openfile(vector<vector<string> >& data, string path) 
{
ifstream inFile;
inFile.open(path);
....

this does not work but it works when i eliminate the path as input

void openfile(vector<vector<string> >& data) 
{
ifstream inFile;
inFile.open("C:\file.csv");
....

i have tried using char path but got the message error conversion from char to const char ..

any help? thanks

Dani AI

Generated

A short expert follow-up that ties the replies together and fills the gaps left by the examples.

As pointed out, older standard-library implementations expected a C-style, null-terminated filename; modern C++ made this easier. C++11 added overloads that accept a std::string for the ifstream/fstream constructors and open(), and C++17 later added overloads that accept std::filesystem::path. Use the standard for your toolchain as appropriate. (en.cppreference.com)

Two practical pitfalls not shown in the original posts: literal escaping and wrong working directory. A literal like "C:\file.csv" contains escape sequences (for example \f) and thus is not what it looks like in source — either escape backslashes ("C:\\file.csv"), use forward slashes ("C:/file.csv"), or use a raw string literal (C++11+) R"(C:\file.csv)". On Windows the runtime will accept forward slashes in most file APIs. (en.cppreference.com)

A robust pattern (modern C++) is to construct the stream with your filename and then verify the stream state before reading:

#include <fstream>
#include <iostream>

std::ifstream inFile(path);   // requires a C++11+ overload for std::string (or C++17 for filesystem::path)
if (!inFile.is_open()) {
    std::cerr << "Failed to open: " << path << '\n';
    return;
}
// proceed to read lines...

Check the stream with is_open() or test the stream object to detect errors early. (en.cppreference.com)

Additional notes: when debugging, prefer absolute paths to rule out working-directory issues; if stuck on an older compiler either enable its C++11+ mode or convert the std::string to a C-style string for that build. Also consider std::filesystem (C++17) for cross-platform path handling when available.

Recommended Answers

All 2 Replies

open() function takes a char*, not a std::string.

inFile.open(path.c_str());

Got ya. Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.