编译器错误消息“错误:无法从'std::string* {aka std::basic_string<char>*}'转换为'std::string {aka std::basic_string<char>}'|”

Compiler error message "error: could not convert from 'std::string* {aka std::basic_string<char>*}' to 'std::string {aka std::basic_string<char>}'|"

提问人:SaltyCode 提问时间:10/28/2016 最后编辑:Peter MortensenSaltyCode 更新时间:11/15/2023 访问量:14250

问:

我正在尝试制作一个写入文件的函数,但是在将字符串作为参数传递时遇到问题。

void writeFile(string filename, string letters, int size)
{
     ofstream outputfile("output.txt");
     outputfile << letters;
     outputfile.close();
 }

int main()
{
    string letters[] = {"u", "l", "s", "n", "m", "z", "a", "p", "b"};

    int size = 9;

    string filename = "Inputfile.txt";

    writeFile(inputfilename.c_str(), letters, size);

}

我收到此错误:

错误:无法从“std::string* {aka std::basic_string*}”转换为“std::string {aka std::basic_string}”|

C++ 指针 参数传递 writefile c-str

评论

0赞 songyuanyao 10/28/2016
什么是 ?unsortedValues
0赞 Barmar 10/28/2016
变量在哪里?该错误指示它是 而不是 .unsortedValuesstring*string
0赞 Barmar 10/28/2016
应该这样吗?lettersunsortedValues
0赞 Barmar 10/28/2016
当参数应该是 a 而不是 C 字符串时,为什么要使用?inputfilename.c_str()filenamestd::string
1赞 Barmar 10/28/2016
@SaltyCode只想将一个字符串写入文件,但你给它一个数组。错误消息对此非常清楚。writeFile()

答:

3赞 Cheers and hth. - Alf 10/28/2016 #1

项目数组作为实际参数传递,其中形式参数是单个 .stringstring

您可以将数组替换为单个字符串。

或者使用集合,或任何适合目的的东西,但您必须相应地更改被调用的函数。


该错误提到的不是数组,例如 ,因为数组表达式衰减为表示指向第一项的指针的表达式,之所以这样做,是因为数组未绑定到引用或传递到表达式的数组性质必须保留的任何内容。std::string*std::string[9]sizeof

0赞 SaltyCode 10/28/2016 #2

问题是

void writeFile(string filename, string letters, int size)

期待一个字符串,但是,

string letters[] = {"u", "l", "s", "n","m", "z", "a", "p", "b"};

是字符串的数组。我通过将函数第二个参数更改为

void writeFile(string outputFileName, string words[], int arraylength)

对于“固定”,我的意思是无论如何,现在它确实创建了一个名为“output.txt”的文件,但内容不是作为第二个参数传递的字符串数组。