Opening file using user input

Hello! I am writing a code for a checkers game and I need to give the user the option to either start a new game, or continue their saved game. We have two text files, one called "newGame.txt" and one called "savedGame.txt". Once the user chooses, fileName is assigned to that file and needs to be opened. Right now I'm getting errors and I'm not sure how to properly assign fileName to the file since this isn't working. If anybody has any advice that would help a lot!

1
2
3
4
5
6
7
8
9
10
11
12
13
char gameType;
    std::string fileName;
    
    std::cout << "Create new game or continue saved game?" << std::endl << "N or S" << std::endl;
    std::cin >> gameType;
    if(gameType == 'N')  {
        fileName = "newGame.txt";
	// Open new game here
        }
    if(gameType == 'S') {
        fileName = "savedGame.txt";
	// Open saved game here
        }
Last edited on
its a lot to retype, try this and if you still don't get it ask specific questions, or tell us what errors you are seeing exactly.

http://www.cplusplus.com/doc/tutorial/files/
Last edited on
The errors I'm getting all say "call to non-static member function without an object argument". So it seems like the assignment for fileName isn't working properly
I'm getting errors and I'm not sure how to properly assign fileName to the file since this isn't working


You need to be much more specific. What errors are you getting? What isn't working?

Is this your actual code, or did you just cut out a small snippet for your post and then further edit your snippet?

It is very difficult to diagnose problems in code that is not shown in your post.

One thing, though, is that the reason you assign the variable fileName is so you can have a single place to open your game file and read in the data. So, the structure of your code would make more sense if it were:

1
2
3
4
5
6
7
8
9
10
11
    if(gameType == 'N')  {
        fileName = "newGame.txt";
    }
    else if(gameType == 'S') {
        fileName = "savedGame.txt";
    }
    else {
        // handle error here
    }

    // open game file here 


I doubt this is the problem you are seeing, but, again, we haven't seen your error messages.
And what line does the error message refer to and is this the only error message being generated?
The errors I'm getting all say "call to non-static member function without an object argument". So it seems like the assignment for fileName isn't working properly


Nothing in your post suggests this problem. Please post your whole code and also post the actual build output.
Nah, you only need an if. Also, your question is too complex. Simplify, man. (Or woman, if you are...)

1
2
3
4
5
6
7
8
9
10
11
12
13
  std::ifstream f;
  {
    std::cout << "Continue saved game? ";
    std::string s;
    getline( std::cin, s );
    // (The first non-whitespace character must be a 'Y' or 'y':
    auto n = s.find_first_not_of( " \t\n\r\v" );
    if (n != s.npos and std::toupper( s[ n ] ) == 'Y')
      f.open( "savedGame.txt" );
    else 
      f.open( "newGame.txt" );
  }
  if (f) ...


A comment, though: why do you have to open a file for a new game?

You should be creating your gameboard/game state in-memory when the program starts. Only if the user wishes to continue a saved game do you need to open a file and use it to set the gameboard/game state.

Hope this helps.
Here is my entire code. I did change the portion I posted so it uses string now, however that doesn't affect the errors I'm given. All of the errors state: "call to non-static member function without an object argument" and they are lines 256, 302, 304, 305:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// 
// 
// Lab 05 - Checkers Program

// Compile with clang++ -Wall -std=c++11 checkersLab05.cpp

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <cstring>
#include <cstdlib>

enum ChipColor {      // value as int EMPTY==0 RED==1 BLACK==2
	EMPTY, RED, BLACK
};
enum ChipRank {    // value as int NOTKING==0 KING==1
	NOTKING, KING
};

enum SquareColor {   // value as int WHITE_SQUARE=0 BLACK_SQUARE=1
        WHITE_SQUARE, BLACK_SQUARE
};

// Square class defines a square on a checkers board 
class Square{

    public:
        Square();
        Square(ChipColor newColor, ChipRank newRank, SquareColor newSqColor); 
        void setColor(ChipColor newColor);
        void setRank(ChipRank newRank);
        void setSquareColor(SquareColor newSqColor);
        ChipColor getChipColor();
        char displayChipColor();
        char saveChipColor();
        char saveChipRank();
        char saveSquareColor();

    private:
        ChipColor chipColor;
        ChipRank chipRank;
        SquareColor squareColor;
};

// Your square member function code goes here        

Square::Square(){
        chipColor = EMPTY;
        chipRank = NOTKING;
        squareColor = WHITE_SQUARE;
}
        

Square::Square(ChipColor newColor, ChipRank newRank, SquareColor newSqColor){ 
        chipColor = newColor;
        chipRank = newRank;
        squareColor = newSqColor;
}

void Square::setColor(ChipColor newColor){
        chipColor = newColor;
}


void Square::setRank(ChipRank newRank){
        chipRank = newRank;
}

void Square::setSquareColor(SquareColor newSqColor){
        squareColor = newSqColor;
}


ChipColor Square::getChipColor(){
    return chipColor;
}

char Square::displayChipColor(){

    char color;
   
    if (chipColor == EMPTY)
        color = ' ';
    if (chipColor == RED)
        color = 'R';
    if (chipColor == BLACK)
        color = 'B';

    return color;
}

char Square::saveChipColor(){

    char color;
   
    if (chipColor == EMPTY)
        color = '0';
    if (chipColor == RED)
        color = '1';
    if (chipColor == BLACK)
        color = '2';

    return color;
}

char Square::saveChipRank()  {
    
    char rank;
    
    if(chipRank == NOTKING)
        rank = '0';
    if(chipRank == KING)
        rank = '1';
        
    return rank;
    }
    
char Square::saveSquareColor()  {
    
    char color;
    
    if(squareColor == WHITE_SQUARE)
        color = '0';
    if(squareColor == BLACK_SQUARE)
        color = '1';
        
    return color;
    }


// Board class defines an 8x8 board
class Board {
    
    public:
        Board();
        void displayBoard();
        void setupBoard(std::string fileName);
        void SaveBoard(std::string fileName);
 
    private:
        int boardSize = 8;
        Square board[8][8];
};


// Your Board member function code goes here        


Board::Board(){
    
   int i=0;
   int j=0;
   int color;
    
   for (i=0; i<boardSize; ++i){
       color = (i) % 2;          // Mod 2 - needed to distinguish white and black squares
       for (j=0; j<boardSize; ++j){
          if ( (j + color) %2 ){
              board[i][j].setSquareColor(WHITE_SQUARE); 
          }
          else{
              board[i][j].setSquareColor(BLACK_SQUARE); 
          }
      }
   }
}



// This function is provided for you
//
// display an 8x8 board of squares like the following:
//
//  +-----+-----+-----+...
//  |*****|     |*****|
//  |* x *|     |* x *|
//  |*****|     |*****|
//  +-----+-----+-----+...
//
//   where the square with the x in it is a black square where the x indicates the color (empty, R or B) 
//   and the blank squares are just spaces; 

void Board::displayBoard(){
   std::string dashes = "+-----";      //characters for square top and bottom bounds
   std::string spaces = "|     ";      //fill for white squares
   std::string stars = "|*****";       // fill for black squares
   std::string line = "";
   std::string filler;
   int i,j,color;
 
    for (i=0; i < boardSize; i++){   //repeat 8 times, once for each row of squares 
        
        line="";  
        for (j=0; j < boardSize; j++){     //build line of cells for boundary  ( +---+ )
            line = line + dashes;
        }
        std::cout << line << "+" << std::endl;
        
        color = (i) % 2;          // Mod 2 - needed to distinguish white and black squares

        line="";                       
        for (j=0; j < boardSize; j++){     //build first line for row of square
            if ( (j + color) %2 ){
                filler = spaces;        // fill spaces for white squares    ( |   |)
            }
            else{
                filler = stars;        // fill stars for black squares     ( |***|)
            }
            line = line + filler;
        }

        std::cout << line << "|" << std::endl;
      

        line="";
        for (j=0; j < boardSize; j++){             //build second line for row of square ( | x | )
            if ((j + color) % 2 ){
               filler = spaces;        // fill spaces for white squares    ( |   |)
            }
            else{
               filler = "|**";                   // fill spaces for blacksquares
               filler += board[i][j].displayChipColor();   // display color of checker
               filler += "**";          
          }
          line = line + filler;
        }
        std::cout << line << "|" << std::endl;
      
        line="";
        for (j=0; j < boardSize; j++){              //build third line for row of square 
           if ( (j + color) %2 ){
                filler = spaces;        // fill spaces for white squares   ( |   | )
            }
            else{
                filler = stars;        // fill stars for black squares   ( |***| )
            }
            line = line + filler;
        }
        std::cout << line << "|" << std::endl;
   }
   

        line="";  
        for (j=0; j < boardSize; j++){     //build line of cells for boundary on bottom of board   ( +---+ )
            line = line + dashes;
        }
        std::cout << line << "+" << std::endl;
        
        std::cout << std::endl;

}

void Board::setupBoard(std::string fileName)   {
    std::ifstream inf;
    inf.open(fileName);
    if(!inf.is_open())   {
        std::cout << "Sorry, could not open file." << std::endl;
	    exit(0);
    }
}

void Board::SaveBoard(std::string fileName)   {
    std::ofstream fout;
    fout.open(fileName);
    if(!fout)   {
        std::cout << "Sorry could not save game." << std::endl;
        exit(0);
        }
    for (int i = 0; i < 8; i++)  {
        for (int j = 0; j < 8; j++)  {
            fout << board[i][j].saveChipColor() << ' ';
            fout << board[i][j].saveChipRank() << ' ';
            fout << board[i][j].saveSquareColor() << ' ';
            fout << "0";
            fout << std::endl;
        }
    }
    fout.close();
    return;
}

 
int main(){
    
    Board gameBoard;
    
    gameBoard.displayBoard();
    
    std::ifstream inputFile;
    std::string fileName;
    
    std::cout << "Please enter the file name:" << std::endl << "newGame.txt or savedGame.txt" << std::endl;
    getline(std::cin, fileName);
    inputFile.open(fileName);
    if(!inputFile.is_open())    {
        std::cout << "Sorry, could not load game." << std::endl;
        exit(0);
        }
    
    gameBoard.setupBoard(fileName);
    
    gameBoard = Board::SaveBoard(fileName);
    Board::SaveBoard(fileName);

   
    Square firstSquare;
    Square secondSquare(RED, NOTKING, BLACK_SQUARE);

    std::cout  <<  firstSquare.getChipColor() << std::endl;  
    std::cout  <<  secondSquare.getChipColor() << std::endl;
    
    return 0;

}
Last edited on
Looks like you're not compiling using C++11 (or higher). Check your compiler settings, using a std::string for the open() of a file stream wasn't added until C++11.

In Line 254 you're opening a ifstream in a method.
This ifstream isn't a static object, it will be lost after this method!
You should close your data-sessions after using.

Do you want to check your file twice? Maybe you should check Line 257 and 296!
1
2
gameBoard = Board::SaveBoard(fileName);
Board::SaveBoard(fileName);

class Board doesn't have a static function SaveBoard.
Also why do you call it twice ?

There are also some warnings that should be fixed.
main.cpp(120): warning C4701: potentially uninitialized local variable 'rank' used
main.cpp(94): warning C4701: potentially uninitialized local variable 'color' used
main.cpp(108): warning C4701: potentially uninitialized local variable 'color' used
main.cpp(132): warning C4701: potentially uninitialized local variable 'color' used
Thank-you for posting your entire code. Now we can see that the location of the errors you mentioned in your first post are not related to the lines of code you posted in your first post.

All of the errors state: "call to non-static member function without an object argument" and they are lines 256, 302, 304, 305:


I think you still edited your code a little bit from the original. The error message locations your provided (again, we would prefer the actual messages pasted into your post rather than you retyping them) don't line up with the code you provided. Specifically, lines 302 and 305 are blank lines.

Line 301 (which I'm guessing lines up with error line 302) does have an object, so I don't see how that can map to the error message you provided.

The error line 256 probably lines up with code line 256. Again, there is an object here, so I don't see how that can map to the error message you provided. As previous posters said, you need to either use C++11 or change inf.open(fileName); to inf.open(fileName.c_str());. But that is not really a member function without an object situation.

Edit: By the way, I went to the online compiler (click the gear symbol next to your code) and compiled your code. I only got error messages for lines 303 and 304 (related to your error lines 304 and 305). I didn't see your other errors.
Last edited on
Topic archived. No new replies allowed.