Just what is probably a basic question for something I haven't been able to figure out all day. Here's a snippet of code in C++:
Escape::Escape(std::string filename)
{
std::ifstream file;
file.open(filename.c_str());
if (file.is_open()) {
file >> gridWidth >> gridHeight >> nKeys;
std::cout << "gridWidth = " << gridWidth << std::endl;
std::cout << "gridHeight = " << gridHeight << std::endl;
std::cout << "nKeys = " << nKeys << std::endl;
/* irrelevant code below */
Basically I want this code to read the first three integers of a text file and save them into the variables gridWidth, gridHeight, and nKeys. These are private integers of a class called "Escape". Here are the first few lines of the text file:
8
8
1
BUL--/EUR--/BUL--/BU---/BU---/BU---/BU---/BUR--/
(more text below)
And here is some sample output of this code:
gridWidth = 107764358
gridHeight = -991553646
nKeys = 0
On running this code multiple times, gridWidth
and gridHeight
are always junk and nKeys is always 0. Any ideas as to what I am doing wrong?
EDIT: The problem was with the filename I passed to file.open()
. I passed in the relative filename which, although openable, was not linkable to the ifstream. The problem was resolved by using the text file's absolute filename instead.
Instead of file >> gridWidth >> gridHeight >> nKeys;
do this instead:
while(file >> gridWidth && file >> gridHeight && file >> nKeys)
This would be better than storing the results in a string and then having to do a conversion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.