问题
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.
回答1:
Thank you for posting your code; now the problem is readily apparent.
You should use string objects, not pointers to them.
FILE *FileOpen(string fname, string mode)
{
string str = "";
str += "tmp/"; //all files to be created in temporary sub directory
str += fname;
FILE *fp = fopen(str.c_str(), mode.c_str());
if (!fp) {
fprintf(stderr, "Cannot open file: %s\n", fname.c_str());
exit(1);
}
FileReader(fname);
return fp;
}
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 a FILE*
and not care what the filename is (except perhaps for generation of error messages).
回答2:
You haven't shown any code, but I suspect you had something like this
char *s1 = "Hello, ", *s2 = "world!";
char buf[50];
strcpy(buf, s1);
strcat(buf, s2);
and now you changed it to
char *s1 = "Hello, ", *s2 = "world!";
char buf[50];
buf = s1 + s2;
This doesn't work, as you already noticed. You must change the char pointers and char array to std::string
as well
std::string s1 = "Hello, ", s2 = "world!";
std::string buf = s1 + s2;
回答3:
If your code is using char *
as strings, then strcat
is probably the right function for you. Of course, the C++ solution is to use std::string
, in which case you can just use +
- since there is binary operator+
available for std::string
.
回答4:
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, but std::string("abc")+"def"
works fine.
alternatively you can write something like
std::string s("abc");
s += "def";
similarly,
std::string s = "abc";
s += "def";
if you want to concatenate a large amount of text, and care about the performance, consider using std::ostringstream
.
来源:https://stackoverflow.com/questions/15056905/strcat-alternative-issue-c