You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++从文本文件读取整数并按三列格式显示的问题

问题解决:游戏分数三列展示错误修复

问题背景

作业要求读取teams.txt文件(每行包含game1、game2、game3三个分数),将分数以三列形式展示,但当前代码运行后所有整数仅单列显示,且换行后重复上一行最后一个数值。

teams.txt 文件内容

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

当前错误代码

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();

错误输出

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

问题原因

  1. 循环逻辑错误:每次循环开始时先输出上一次循环最后读取的score值,导致每行第一个数重复上一行最后一个数。
  2. 输出格式错误:将每个分数单独换行,未实现三列展示的要求。

修复后的代码

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main() {
    ifstream infile("teams.txt");
    
    if (!infile.is_open()) {
        cout << "teams.txt did not open" << endl;
        return -1;
    }
    
    int game1, game2, game3;
    // 一次性读取每行的三个分数,直到文件结束
    while (infile >> game1 >> game2 >> game3) {
        // 设置固定宽度,保证三列对齐,宽度可根据需求调整
        cout << setw(5) << game1 << setw(5) << game2 << setw(5) << game3 << endl;
    }
    
    infile.close();
    return 0;
}

修复说明

  1. 读取逻辑优化:直接一次性读取每行的三个整数,避免重复读取导致的数值重复问题。
  2. 三列展示实现:使用setw()函数(需包含<iomanip>头文件)设置每个分数的输出宽度,确保三列对齐,满足题目要求的展示格式。
  3. 文件判断优化:用!infile.is_open()替代infile.fail(),逻辑更直观清晰。

内容的提问来源于stack exchange,提问作者Kimberly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 08:55:07