I am working on a project which was initially sampled in C but want to work on it in C++.
There is a section where a strcat() is used, I have been told to use an alternative. I have found one here, but when I try those the compiler gives me the following error:
error: invalid operands of types
char*' and
char*' to binary `operator+'
Is there something I am doing wrong?
Edit:
Here's the portion of the code that doesn't work
FILE *FileOpen(string *fname, string* mode){
FILE *fp;
string *str = "";
str += "tmp/"; //all files to be created in temporary sub directory
str += fname;
if((fp=fopen(str,mode))==NULL){
fprintf(stderr,"Cannot open file: %s\n", &fname);
exit(1);
}
FileReader(fname);
return(fp);
}
Edit 2: For those wondering why I have FileReader: it's for part 2 of the project. Disassembling a code.
If your code is using
char *
as strings, thenstrcat
is probably the right function for you. Of course, the C++ solution is to usestd::string
, in which case you can just use+
- since there is binaryoperator+
available forstd::string
.You haven't shown any code, but I suspect you had something like this
and now you changed it to
This doesn't work, as you already noticed. You must change the char pointers and char array to
std::string
as wellThank you for posting your code; now the problem is readily apparent.
You should use string objects, not pointers to them.
A good next step would be to move to I/O functions that accept
std::string
arguments, so you don't have to say.c_str()
everywhere.I'm also confused why you have
FileReader(fname)
inside your file-opening function. That violates the Single-Responsibility-Prinicple, twice. Opening a file should not cause it to be read, and the code reading the file should use aFILE*
and not care what the filename is (except perhaps for generation of error messages).well, C++ has a string class
std::string
whose operator+ performs concatenation. But you have to create one first.so the expression
"abc" + "def"
doesn't compile, butstd::string("abc")+"def"
works fine.alternatively you can write something like
similarly,
if you want to concatenate a large amount of text, and care about the performance, consider using
std::ostringstream
.