尝试将文件写入数组时的运算符<<错误

我正在尝试读取一个文件(该文件可以具有任意数量的数字,但不会超过500个)并将其放入数组中。

稍后,我将需要使用数组处理许多事情。

但是到目前为止,这小段代码在while循环中给了我no match for operator<<,我不知道该怎么办。

我是新来的,将不胜感激。

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

int main () {
    string line;
    ifstream myfile ("array_pgmdata.txt");
    int index = 0;
    string myArray[index];

  if (myfile.is_open())
  {

    while (! myfile.eof() )
    {
      getline (myfile,line);
      myArray[index++] << line;
    }
  }

  else cout << "Unable to open file"; 

  return 0;
}
weihua109 回答:尝试将文件写入数组时的运算符<<错误

您有Undefined behavior。您正在使用大小为0的VLA并超出范围(即使索引0也将超出范围)。修复和评论:

#include <fstream>
#include <string>
#include <iostream>  // std::cout
#include <vector>

using namespace std; // not recommended

int main () {
    string line;
    ifstream myfile ("array_pgmdata.txt");
    //int index = 0;            // not needed
    //string myArray[index];    // UB - if it even compiles,it's a VLA of size 0.

    std::vector<std::string> myArray;    // use this instead to be able to grow it
                                         // dynamically

    if (myfile)                          // open and in a good state
    {
        // while (! myfile.eof() )       // It'll not be eof when you've read the last line
                                         // only when you try to read beyond the last line,// so you'll add "line" one extra time at the end
                                         // if you use that. Use this instead:
        while(getline(myfile,line))
        {
            // myArray[index++] << line; // you have 0 elements in the array and
                                         // can't add to it in any way
            myArray.push_back(line);
        }
    }
    else cout << "Unable to open file"; 

    // print what we got

    // classic way:
    for(size_t idx=0; idx < myArray.size(); ++idx) {
        std::cout << myArray[idx] << "\n";
    }

    // using a range-based for loop
    for(const std::string& s : myArray) {
        std::cout << s << "\n";
    } 

    // using a range-based for loop with auto
    for(const auto& s : myArray) {               // s is a std::string& here too
        std::cout << s << "\n";
    } 
}

还请注意,myArray[index++] << line不是将字符串分配给字符串的方式。 myArray[index++] = line是正确的方法。我怀疑您曾经使用<<试图将字符串附加到您的VLA,但是您实际尝试使用的是一个看起来像这样的运算符:

std::string& operator<<(std::string& dest,const std::string& src);

不存在(除非您自己添加)。

,

<<类上未定义string运算符。

您只需要在此处进行分配,将myArray[index++] << line;更改为myArray[index++] = line;

您本能使用<<是因为它与coutostringstream之类的其他流一起使用。但是在这里,您只有一个字符串数组,因此您可以像使用其他类型的intchar一样为数组位置分配一个值。

本文链接:https://www.f2er.com/3158654.html

大家都在问