C++ ifstream error using string as opening file path.
Change ifstream file(filename); to ifstream file(filename.c_str()); Because the constructor for an ifstream takes a const char*, not a string pre-C++11.
Change ifstream file(filename); to ifstream file(filename.c_str()); Because the constructor for an ifstream takes a const char*, not a string pre-C++11.
How about this? (KISS solution) void LoadCities() { int x, y; ifstream in(“Cities.txt”); if (!in) { cout << “Cannot open file.\n”; return; } for (y = 0; y < 15; y++) { for (x = 0; x < 15; x++) { in >> distances[x][y]; } } in.close(); } Works for me. Might not be that … Read more
How about this :- std::ifstream inFile(“file”); std::count(std::istreambuf_iterator<char>(inFile), std::istreambuf_iterator<char>(), ‘\n’);
First thing is first, you shouldn’t check like that. eof() doesn’t return true until after a failed read. But you can do better (and easier)! check the stream state with the implicit conversion to void* which can be used in a bool context. Since most of the read operations on streams return a reference to … Read more
There are a couple of things that you can do. First, there’s no problem opening a file that is larger than the amount of RAM that you have. What you won’t be able to do is copy the whole file live into your memory. The best thing would be for you to find a way … Read more
I’m afraid you’ll probably have to rewrite the entire file. Here is how you could do it: #include <iostream> #include <fstream> using namespace std; int main() { string strReplace = “HELLO”; string strNew = “GOODBYE”; ifstream filein(“filein.txt”); //File to read from ofstream fileout(“fileout.txt”); //Temporary file if(!filein || !fileout) { cout << “Error opening files!” << … Read more
An istream treats “white space” as delimiters. It uses a locale to tell it what characters are white space. A locale, in turn, includes a ctype facet that classifies character types. Such a facet could look something like this: #include <locale> #include <iostream> #include <algorithm> #include <iterator> #include <vector> #include <sstream> class my_ctype : public … Read more
You cannot insert in the middle of the file. You have to copy the old file to a new file and insert whatever you want in the middle during copying to the new file. Otherwise, if you intend to overwrite data/lines in the existing file, that is possible by using std::ostream::seekp() to identify the position … Read more
According to cplusplus.com: failbit is generally set by an input operation when the error was related to the internal logic of the operation itself, so other operations on the stream may be possible. While badbit is generally set when the error involves the loss of integrity of the stream, which is likely to persist even … Read more
Use the std::getline() from <string>. istream & getline(istream & is,std::string& str) So, for your case it would be: std::getline(read,x);