strcat的替代问题C ++ [英] strcat alternative issue C++

查看:518
本文介绍了strcat的替代问题C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我使用的是一个使用strcat()的部分。 ,我被告知要使用一种替代品。我在这里找到一个这里 ,但是当我尝试那些编译器给我以下错误:


错误:类型的无效操作数 '和 char *'到二进制`operator +'


p>

编辑:



以下是无效的代码部分

  FILE * FileOpen(string * fname,string * mode){
FILE * fp;
string * str =;

str + =tmp /; //所有要在临时子目录中创建的文件
str + = fname;
if((fp = fopen(str,mode))== NULL){
fprintf(stderr,无法打开文件:%s\\\
,& fname);
exit(1);
}
FileReader(fname);
return(fp);
}

编辑2:
对于那些想知道为什么我有FileReader:为项目的第2部分。

解决方案

感谢您发布代码;现在问题很明显。



您应该使用字符串对象,而不是指向它们的指针。

  FILE * FileOpen(string fname,string mode)
{
string str =;

str + =tmp /; //所有要在临时子目录中创建的文件
str + = fname;
FILE * fp = fopen(str.c_str(),mode.c_str());
if(!fp){
fprintf(stderr,无法打开文件:%s\\\
,fname.c_str());
exit(1);
}
FileReader(fname);
return fp;
}

一个好的下一步是移动到接受 std :: string 参数,所以你不必说 .c_str()无处不在。



我也困惑为什么你的文件打开函数中有 FileReader(fname)。这违反了单一责任 - 原则,两次。打开文件不应该导致它被读取,并且读取文件的代码应该使用 FILE * ,而不关心文件名是什么(除了生成错误消息)。


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*' andchar*' 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.

解决方案

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).

这篇关于strcat的替代问题C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆