C++ 追加到数组

C++ Appending to an array

本文关键字:数组 追加 C++      更新时间:2023-10-16
const int fileLength = fileContent.length();
    char test[1000];
    for (int p = 0; p < fileLength; ++p){
        test[p].append(fileContent[p]); // Error: expression must have class type
    };

正在尝试将文本文件的字符附加到我创建的数组中。虽然我收到错误" 表达式必须具有类类型 "。尝试谷歌搜索此错误无济于事。

test是一个字符数组。 test[p]是炭。 char没有任何成员。 特别是,它没有append成员。

您可能希望使测试成为std::vector<char>

    const auto fileLength = fileContent.length();
    std::vector<char> test;
    for (const auto ch : fileContent)
    {
        test.push_back(ch);
    }

甚至:

    std::vector<char> test( fileContent.begin(), fileContent.end() );

如果你真的需要将test视为一个数组(例如,因为你正在与某个 C 函数接口(,那么使用:

    char* test_pointer = &*test.begin();

如果你想把它用作一个以 nul 结尾的字符串,那么你可能应该使用 std::string 代替,并获取带有 test.c_str() 的指针。

char 数组没有任何名称为 append 的成员函数。然而,std::string确实有一个名为append的成员函数,如下所示:

string& append (const char* s, size_t n);

我认为您错误地使用了字符数组而不是 std::string .std::string将解决此问题,如下所示:

const int fileLength = fileContent.length();
    string test;
    for (int p = 0; p < fileLength; ++p){
        test.append(fileContent[p],1); // Error: expression must have class type
    };

更好的方法是字符串测试(文件内容(。您可以像访问数组一样访问测试。有关更多详细信息,请参阅字符串类。