无法将数据从文本文件读入数组

时间:2017-10-15 20:20:12

标签: c++ arrays netbeans text-files

我的程序没有打印我想要打印的内容。

#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

如果我注释掉得分数组的打印,则输出后跟多个空白行。我操纵了for循环的参数,似乎没有任何工作正常。有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

utcnow()

您希望在一行上有一个整数。阅读整行并转换为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
}
相关问题