File Input & Output in C++: Why Use a String Literal?

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
7 replies · 3K views
Whovian
Messages
651
Reaction score
3
I felt like learning a bit about file input and output in C++. Tried some code, couldn't get it to work unless I made the path to the file a string literal, not a variable type. Why is this, and is there any way to get a string data type to be inputted as a path?
 
Physics news on Phys.org
Whovian said:
I felt like learning a bit about file input and output in C++. Tried some code, couldn't get it to work unless I made the path to the file a string literal, not a variable type. Why is this, and is there any way to get a string data type to be inputted as a path?

I'm assuming you tried something like:
Code:
std::string filename("/path/to/file");
std::ifstream ifs(filename);
Did you?

If so, try:
Code:
std::string filename("/path/to/file");
std::ifstream ifs(filename.c_str());
 
I tried

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

int main()
{
	string file = "Documents/Programming/C++.txt";
	string contents;
	ifstream in;
	ofstream out;
	out.open(file);
	out << "This is a C++ program here." << endl;
	out.close();
	in.open(file);
	getline(in,contents);
	in.close();
	cout << contents << endl;
	return 0;
	}

Note that I'm on a MAC, so that is a valid path. Using file.c_str seemed to work, thanks!
 
You'd think that the C++ ifstream constructor could take a C++ string as its argument. My understanding is that it's a backward-compatibility issue with ancient versions of C++ that pre-date the first standardized version (in which the 'string' data type was introduced).
 
You'd still think you could create another constructor that takes a string object; I don't see how any backwards compatibility issues would occur.
 
jhae2.718 said:
You'd still think you could create another constructor that takes a string object; I don't see how any backwards compatibility issues would occur.

Agreed.

You'd think they would have fixed this in C++03, but they didn't.
I wonder why, since they must have discussed this.

Anyway, apparently it is finally fixed in C++11.