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

后端 未结 3 2030
傲寒
傲寒 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 words (numWords);
    
    while(repFile >> x)
        words.push_back(x);
    

    Change to:

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

    or:

    vector 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 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();
    }
    

提交回复
热议问题