将字符串 class 转换为 CString 时出错

Error in String class to CString Conversion

我想将三个字符串变量放在一个数组中,并作为CString 彼此相邻。此代码给我一个声明错误。

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string Str1, Str2, Str3;
    cin >> Str1 >> Str2 >> Str3;

    int length_Str1 = Str1.size(), length_Str2 = Str2.size(), length_Str3 = Str3.size();
    char aCString[length_Str1+length_Str2+length_Str3+1];

    string Str_Array [] = {Str1, Str2, Str3};
    strcpy(aCString, Str_Array.c_str());

    return 0;
}

错误:

代码中有两个错误:

1. 14:32: error: request for member 'c_str' in 'Str_Array', which is of non-class type 'std::string [3] {aka std::basic_string<char> [3]}' 2. 14:39: error: 'strcpy' was not declared in this scope

原因:

  • First error was because you were trying to call c_str for a Str_Array which is a pointer to the array of strings, the right way is to call it for a string itself i.e. Str_Array[someIndexOfArray]
  • Reason behind the second error was that string.h which contains the method strcpy was not included in the program.

解法:

试试下面的代码:

#include <iostream>
#include <string>

#include <string.h>     //for strcpy and strcat method

using namespace std;

int main()
{
    string Str1, Str2, Str3;
    cin >> Str1 >> Str2 >> Str3;

    int length_Str1 = Str1.size();
    int length_Str2 = Str2.size();
    int length_Str3 = Str3.size();

    char aCString[length_Str1+length_Str2+length_Str3+1];

    string Str_Array[] = {Str1, Str2, Str3};

    strcpy(aCString, Str_Array[0].c_str()); //copy the first index of array 

    for(int i =1;i<3;i++)   //concatenate each index of array
        strcat(aCString, Str_Array[i].c_str());

    return 0;
}

希望这对您有所帮助。