Please explain this code which uses stringstream and stat function.


Hello ,

I am running through a game program code and it says

1.bool keyboardcontroller::loadboard(int boardnumber)
2.{
3.stringstream sin;
4.sin<<boardsDir<<boardNumber<<".txt";
5.if(stat(sin.str().c_str(),&st) == 0)
6.{

7.printf("Loading board = %s \n",sin.str().c_str());\
8.return true;
9.}
10.else
11.return false;
}

we give boardnumber as 1 to the above function and boardsDir contains a directory called boards which contains 1.txt,2.txt,... as levels .
we increase the boardnumber as game progresses.

I have very hard time understanding the code present in the lines 4 and 5 .
Another thing is that line 7 is printing "Loading board boards/1.txt" on console.

Thanks and Regards.

closed account (o3hC5Di1)
Hi there,

here's a line for line explanation of the code for you:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//define keyboardcontroller member method loadBoard, returning a boolean value and taking an int as an argument
bool keyboardcontroller::loadboard(int boardnumber)
{
    //declare a stringstream called sin
    stringstream sin;
    //concatenate boardsDir, boardsNumber and ".txt" and insert into the stringstream
    sin<<boardsDir<<boardNumber<<".txt";
    //stat() returns 0 if it can load the file's information, i.e. if it exists
    if(stat(sin.str().c_str(),&st) == 0)
    {
        //if the file exists, print "Loading Board =" + the c-character sequence of stringstream sin
        printf("Loading board = %s \n",sin.str().c_str());\
        //return true and exit function
        return true;
    }
    // if the file does not exist, return false and exit the function
    else
    {
        return false;
    }
}


If you need further information on the functions used, check out these links:

http://msdn.microsoft.com/en-us/library/14h5k7ff.aspx
http://www.cplusplus.com/reference/string/string/c_str/
http://www.cplusplus.com/reference/iostream/stringstream/str/

Hope that helps.

All the best,
NwN
Last edited on
Topic archived. No new replies allowed.