我的程序没有打印我想要它打印的内容。
#include<cstdlib>
#include<cmath>
#include<fstream>
#include<sstream>
#include<iomanip>
#include<iostream>
#include<string>
#include<cstring>
#include<cassert>
#include<ctime>
#include<cctype>
#include<algorithm>
#include<locale.h>
#include<stdio.h>
#include<functional>
#include<math.h>
using namespace std;
int main(int argc, char**argv)
{
int r = 0;
int p = 0;
int c = 0;
string names[20];
double scores[20][10];
ifstream infile;
infile.open("C:\\Users\\Colin\\Documents\\NetBeansProjects\\Bowlerspart2\\data\\bowlers.txt");
while(!infile)
{
cout << "can not find file" << endl;
return 1;
}
for(r = 1; r <= 10; r++)
{
getline(infile, names[r]);
for(c = 1; c <= 3; c++)
{
infile >> scores[r][c];
}
}
infile.close();
for(r = 1; r <= 10; r++)
{
cout << names[r] << endl;
cout << fixed << setprecision(2) << endl;
cout << scores[r][c] << endl;
}
return 0;
}
它只打印其中一个名字,并为所有分数打印 0.00。我相信我可能读错了文件,但不确定如何读错。
这是文本文件:
Linus too good
100
23
210
Charlie brown
1
2
12
Snoopy
300
300
100
Peperment Patty
223
300
221
Pig Pen
234
123
212
Red Headed Girl
123
222
111
Marcey
1
2
3
Keith hallmark
300
300
250
Anna hallmark
222
111
211
Roxie hallmark
100
100
2
这是我的代码得到的输出:
Linus too good
0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00
如果我注释掉 scores 数组的打印,则输出后跟多个空行。我操纵了 for 循环的参数,但似乎没有任何效果。有人能指出我正确的方向吗?
最佳答案
for(c = 1; c <= 3; c++)
{
infile >> scores[r][c];
}
您希望在一行中有一个整数。阅读整行并转换为 double
:
for(c = 1; c <= 3; c++)
{
string temp;
getline(infile, temp);
scores[r][c] = std::stod(temp);
}
您的打印功能保持打印相同 scores[r][c]
它存储初始化值(在本例中为零)。你忘了像这样遍历值:
for(r = 1; r <= 10; r++)
{
cout << names[r] << endl;
cout << fixed << setprecision(2) << endl;
for (c = 1; c <= 3; c++)
cout << scores[r][c] << endl;
}
请注意 scores[r][c] = std::stod(temp);
如果 temp
则需要异常处理无法转换为 double
.
try
{
scores[r][c] = std::stod(temp);
}
catch(...)
{
//add error handling
}
您可以添加额外的错误处理并按照评论中的建议从零索引开始
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
...
for(int r = 0; r < 10; r++)
{
if(!getline(infile, names[r]))
break;
for(int c = 0; c < 3; c++)
{
string temp;
if(!getline(infile, temp))
break;
try
{
scores[r][c] = std::stod(temp);
}
catch(...)
{
}
}
}
for(int r = 0; r < 10; r++)
{
cout << names[r] << endl;
cout << fixed << setprecision(2) << endl;
for (int c = 0; c < 3; c++)
cout << scores[r][c] << endl;
}
关于c++ - 无法将文本文件中的数据读入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46759598/