问题描述:

Im viewing some old code that has no comments which I try to understand, the code:

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;

}

It returns a vector with lines of text. I understand all the code except the part where char c is used and the value 256.

char c[256];

and

myFile.getline(c, 256);

What is the purpose of the value 256?

网友答案:

The reference explains everything that you need to know. We can read that the parameters are:

Parameters

s - pointer to the character string to store the characters to

count - size of character string pointed to by s

and we can also read:

[...] extracts characters from *this and stores them in successive locations of the array whose first element is pointed to by s, until any of the following occurs (tested in the order shown):

[...]

  • count-1 characters have been extracted (in which case setstate(failbit) is executed).

So, the second argument is used to make sure that getline doesn't try to read and insert more than 255 characters into your buffer c. Inserting more than 255 characters will result in undefined behavior.

相关阅读:
Top