getLine中的c ++ char c [256]

时间:2017-01-20 17:14:33

标签: c++

我正在查看一些没有我试图理解的评论的旧代码,代码:

std::vector<std::string> CardFactory::readFile(std::string fileName)
{
    std::vector<std::string> returnVal;
    std::ifstream myFile;
    myFile.open(fileName);
    if (myFile.is_open())
    {
        std::vector<string> textLines;
        char c[256];
        //not sure why the line below this is not in the while loop
        myFile.getline(c, 256);
        while (myFile.good()) {
            string line = string(c);
            textLines.push_back(line);
            myFile.getline(c, 256);
        }
        myFile.close();
        return textLines;
    }
    else
    {
        std::cout << "File not open " << std::endl;
        return std::vector<string>();
    }
    return returnVal;
}

它返回带有文本行的向量。我理解除了使用char c的部分和值​​256之外的所有代码。

char c[256];

myFile.getline(c, 256);

值256的目的是什么?

1 个答案:

答案 0 :(得分:1)

reference解释了您需要知道的一切。我们可以读到参数是:

  

<强>参数

     

s - 指向将字符存储到

的字符串的指针      

count - s

指向的字符串的大小

我们也可以阅读:

  

[...]从* this中提取字符并将它们存储在连续的位置   其中第一个元素由s指向的数组,直到任何一个   发生以下情况(按所示顺序测试):

     

[...]

     
      
  • 已提取count-1个字符(在这种情况下)   setstate(failbit)被执行)。
  •   

因此,第二个参数用于确保getline不会尝试读取并在缓冲区c中插入超过255个字符。插入超过255个字符将导致未定义的行为。