This has worked fine on some compilers... Is there a way of doing this were it will just work without it being a problem with different compilers on c++11 or c++14?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void save_file() {
string file;
ofstream os;
cout << "Save As: ";
getline(cin, file, '\n');
os.open(file + ".dat");
//rest of code
}
error: no viable conversion from 'basic_string, std::allocator >' to 'const char *'
So I google it, found some answers, or in this case, canswers (cancers), tried
os.open(file.c_str() + ".dat");
error: invalid operands to binary expression ('const char *' and 'const char *')
Accoding to the C++11 standard 27.9.1.10 one of the constructors for a basic_ofstream is:
explicit basic_ofstream(const string& s, ios_base::openmode mode = ios_base::out);
This means that any standard compliant compiler should be able to compile:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string file = "temp";
ofstream os;
os.open(file + ".dat");
}
Live Example
Don't forget that you need to use the -std=c++11 or higher flag when compiling.
"+" operator cannot be used for the C-style strings. Try this:
string name = file+".dat";
os.open(name.c_str());
You create the std::string type as a concatenation in c++ style and then pass it to open as a c string.
In C++11, os.open( file + ".dat" ) works just fine. Pre C++11, there was no std::ofstream::open which took a string, so you had to write os.open( (file + ".dat").c_str() ). Note the parentheses and where the .c_str() goes---you have to concatenate with the std::string first, and only call .c_str() on the results.
Related
so I want to create a file but the name of it will be dependent on the user input e.g. if the user types "shrek" the file must be named "shrek.txt". Thats what I came up with but it doesn't work.
int main(){
ofstream file;
string name = "abc";
file.open(name + ".txt");
file.close();
}
I guess you are using an old C++ standard. If that's the case, fstream::open won't accept a std::string, only a C string (char*). You can use c_str in your string to obtain a const char* that will be accepted:
int main(){
ofstream file;
string name = "abc";
string file_name = name + ".txt";
file.open(file_name.c_str()); // <- here
file.close();
}
However, it's recommendable to switch to a more modern standard, as your code actually works for C++11 and newer.
Do you have the libraries required? In this case #include fstream. Does the same issue happens to another complier? Check that out. I attempted this myself and your code surely works. Attempt to use my code which I confirm works and see if you have any issues.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string name;
cin>> name;
ofstream file(name +".txt");
file.close();
}
Can't compile this small code on Linux:
#include <fstream>
#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;
int main(){
char fileName[512];
sprintf(fileName, "test");
ofstream iriFile(string(fileName));
iriFile<<",";
return 0;
}
I am compiling like this: g++ test.cpp and am getting this:
test.cpp:12:11: error: invalid operands of types
‘std::ofstream(std::__cxx11::string) {aka
std::basic_ofstream(std::__cxx11::basic_string)}’ and
‘const char [2]’ to binary ‘operator<<’ iriFile<<",";
What might be the reason?
Ok, the solution is to remove implicit string() creation:
string sFileName(fileName)
ofstream iriFile(sFileName);
First of all you do not need to explicitly convert const char * to std::string there is std::ifstream constructor for it:
std::ofstream iriFile(fileName);
but if you want to be extra safe and verbose use proper C++ then:
std::ofstream iriFile( static_cast<std::string>(fileName) );
not C style cast.
As you pointed out, removing the explicit string creation fixes it.
It could be worth to add that this can also be fixed for types with explicit constructors by using list initialization, like so:
ofstream iriFile(string{sFileName});
I'm experimenting with C++ file I/O, specifically fstream. I wrote the following bit of code and as of right now it is telling me that there is no getline member function. I have been told (and insisted still) that there is a member function getline. Anybody know how to use the getline member function for fstream? Or perhaps another way of getting one line at a time from a file? I'm taking in two file arguments on the command line with unique file extensions.
./fileIO foo.code foo.encode
#include <fstream>
#include <iostream>
#include <queue>
#include <iomanip>
#include <map>
#include <string>
#include <cassert>
using namespace std;
int main( int argc, char *argv[] )
{
// convert the C-style command line parameter to a C++-style string,
// so that we can do concatenation on it
assert( argc == 2 );
const string foo = argv[1];
string line;string codeFileName = foo + ".code";
ifstream codeFile( codeFileName.c_str(), ios::in );
if( codeFile.is_open())
{
getline(codeFileName, line);
cout << line << endl;
}
else cout << "Unable to open file" << endl;
return 0;
}
getline(codeFileName, line);
Should be
getline(codeFile, line);
You're passing in the file name, not the stream.
By the way, the getline you're using is a free function, not a member function. In fact, one should avoid the member function getline. It's much harder to use, and harkens back to a day when there was no string in the standard library.
Typo
getline(codeFileName, line);
should be
getline(codeFile, line);
I guess the lesson is you have to learn how to interpret compiler error messages. We all make certain kinds of mistakes and learn the compiler errors they tend to generate.
When using ifstream class to read words from an input file, I have used the following expression:
#include <iostream>
#include <fstream>
int main(int argc, char *argv[])
{
std::ifstream inputStream(myFile.txt);
std::string myString;
myFile.open()
while(myFile.good())
{
myFile >> myString;
printf("%s \n", myString);
}
return 0;
}
The contents of myFile.txt are:
" This is a simple program. "
The compiles and executes as expected using g++ compiler.
However, the same code when compiled using msvc 2008, returns error at the extraction operator (>>) requiring me to replace the std::string with either an initialized character array or any of the supported native types.
This threw me off as I was expecting the usage of the standard library to be same across implementations.
I understand the compile error and know the way to fix it via using c_str().
But, it would help me a great deal, if someone could clarify why the usage for the standard library is different across platforms.
To me it is not starndard anymore !!
EDIT: Code updated to be complete. Content of myFile.txt updated.
Chances are that you forgot to #include <string>. Without it, Microsoft's version of <iostream> (and such) include enough of a declaration of std::string for some things to work, but other parts are missing, so you get strange, seemingly inexplicable failures.
One of the things that's missing is most of the operator overloads for std::string, which is exactly what you seem to be missing.
As an aside, while (myfile.good()) ... is pretty much a guaranteed bug -- you probably want:
while (myfile>>myString)
std::cout << myString << " \n";
Alternatively, you could do the job with a standard algorithm:
#include <string>
#include <algorithm>
#include <iterator>
#include <fstream>
#include <iostream>
int main() {
std::ifstream myfile("input.txt");
std::copy(std::istream_iterator<std::string>(myfile),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, " \n"));
return 0;
}
The following compiles fine for me on MSVC 2010:
std::ifstream inputStream;
std::string myString;
inputStream.open("myFile.txt", std::ifstream::in);
while(inputStream.good())
{
inputStream >> myString;
}
Note: without using std::ifstream::in as my open mode, I got the same error as you. I suggest you check what value you have for this parameter.
Goodnight to everyone, I'm trying to parse an .h file so I can have a small console frontend to change its values, but when I try to use strncmp with a string read from a file and a string defined in code to compare with the file string I get a strange error from the compiler that I cant resolve, here is my source code:
//Test to basic file operations
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main (void){
string line;
ifstream myfile("PIDconfig.h");
if(myfile.is_open()){ //if file is open
while(myfile.good()){
getline(myfile, line);
if(strncmp(line, "static float", 12) == 0){
cout << line << endl;
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
And the error that I get:
tiago#tiago-laptop:~$ g++ file.cpp
file.cpp: In function ‘int main()’:
file.cpp:17: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int strncmp(const char*, const char*, size_t)’
If some one could help me I would be very glad, I have already searched StackOverflow but I didnt found anyone with the same problem, almost all strncmp problems use arrays to store their strings and as far as I went, no one was having a problem using it and file I/O.
std::string overloads operator==. You can simply compare two std::string object using ==.
Also, your input loop is incorrect.
the problem is that strncmp() function overloaded for strncmp(const char*, const char*, int)
but you want to call it by strncmp(string, string, size_t)
you must convert string to const char* with
c_str()
for example
string str = "Hello";
char * arr = str.c_str().
you get it?
if(strncmp(line.c_str(), "static float", 12) == 0){
should work
The problem is that you're reading data from the file as a C++ string, and the strncmp function works on C style strings. To fix this, you can either extract a raw C style string from the C++ string using .c_str(), or you can use the C++ string's .compare function:
line.compare(0, 12, "static float")