Search code examples
c++filetextcomputer-science

Moving integers into three columns from a text file in C++


We were told to create a game for an assignment and display it into a chart. We were given a txt. file that displays the game scores as game1, game2, and game3 in columns with the scores. After filling in the code to open the txt. file and display the scores, all the integers display in one column. I don't know how to make them display into three columns.

This is the txt. file to display the scores in three columns to also appear in the output window:

187  162  171
199  123  175
151  126  165
136  121  149
177  181  187
173  173  173
181  188  172
196  197  199
199  200  193
199  200  200
162  171  180
117  162  156
161  179  192
151  159  163
185  184  189
173  169  168
184  189  171
165  141  157
192  194  196
191  163  164
173  174  161
153  141  137
191  196  194
199  200  199
106  104  1
133  142  140
108  106  118

This is my code:

ifstream infile;
        
infile.open("teams.txt");
        
if (infile.fail()) 
    {
        cout << "teams.txt did not open" << endl;
        exit (-1);
    }
                
int score;
                    
infile >> score;
                    
while (infile)
    {
        cout << score << endl;
            
        infile >> score;
        cout << score << endl;
                
        infile >> score;
        cout << score << endl;
                
        cout << endl;
    }
            
infile.close();                     

In the output window, it displays:

187
162
171

171
199
123

123
175
151

151
126
165

165
136
121

121
149
177

177
181
187

187
173
173

173
173
181

181
188
172

172
196
197

197
199
199

199
200
193

193
199
200

200
200
162

162
171
180

180
117
162

162
156
161

161
179
192

192
151
159

159
163
185

185
184
189

189
173
169

169
168
184

184
189
171

171
165
141

141
157
192

192
194
196

196
191
163

163
164
173

173
174
161

161
153
141

141
137
191

191
196
194

194
199
200

200
199
106

106
104
1

1
133
142

142
140
108

108
106
118

118
118
118

As you can see, 187, 162, and 171 are game1, game2, and game3 scores, but appear together instead of separate. Also, I'm not sure why it is repeating the last digit as the first one after the line break.

Any help will be appreciated


Solution

  • Try something more like this:

    ifstream infile("teams.txt");
    if (!infile) 
    {
        cout << "teams.txt did not open" << endl;
        exit (-1);
    }
                    
    int score1, score2, score3;
                        
    while (infile >> score1 >> score2 >> score3)
    {
        // format the output however you want...
        cout << score1 << '\t' << score2 << '\t' << score3 << endl;
    }
                
    infile.close();