Variable length array of non-POD element type 'string' (aka 'basic_string') c++

后端 未结 3 2029
傲寒
傲寒 2021-01-07 10:16

I get this error in my c++ code Variable length array of non-POD element type string (aka basic_string).

string words[n         


        
相关标签:
3条回答
  • 2021-01-07 10:42

    This initializes words with numWords empty strings then appends the actual strings afterwards:

    vector<string> words (numWords);
    
    while(repFile >> x)
        words.push_back(x);
    

    Change to:

    vector<string> words;
    
    while(repFile >> x)
        words.push_back(x);
    

    or:

    vector<string> words (numWords);
    
    int idx = 0;
    while(repFile >> x /* && idx < numWords */)
        words[idx++] = x;
    

    EDIT:

    There is no reason to count the number of words before populating the vector:

    vector<string> words;
    ifstream repFile("//Users//bobthemac//Documents//c++asignment//c++asignment//test1.txt");
    if (repFile.is_open())
    {
        while(repFile >> x)
        {
            words.push_back(x);
        }
        repFile.close();
    }
    
    0 讨论(0)
  • 2021-01-07 11:01

    C++ doesn't have C99-style variable length arrays. Your compiler might support them as an extension, but they're not part of the language. In this specific case, your success with Visual Studio indicates that it does in fact have such an extension. clang++ will support VLAs, but only of POD types, so your attempt to make a VLA of string objects won't work. g++ does work on my machine if I leave off enough warning/error flags.

    0 讨论(0)
  • 2021-01-07 11:07

    Sorry, you need to write gcc --version to get the version.

    As others state, you shouldn't use variable-length arrays, but GCC does support them as an extension in C++. My GCC 4.4.4 compiles just fine with the following code:

    #include <string>
    #include <iostream>
    using namespace std;
    
    int main() {
      int n;
      cin >> n;
      string s[n];
      return 0;
    }
    

    Does that code compile for you? If it does, then you need to give us the smallest piece of code that fails.

    The best solution, though, is to use vector<string>.

    0 讨论(0)
提交回复
热议问题