如何将文件中的数据读入数组

时间:2013-12-11 00:42:44

标签: c++ arrays

我有这个程序从数据文件中获取属性并将它们输入到程序中的计算中。这是我目前的代码,但它没有采用任何值...任何帮助表示赞赏

float woodcharacStrength(){
    myInfile.open ("strength_classes.txt");     //inputs external file that contains characteristic values for forces parallel to grain.

    for (row = 0; row<3; row++)
        for (col = 0; col<18; col++)            //condition to only read certain rows and columns of the input file
        {
myInfile >> arraylocation[row][col];        //used to define each value of the array
        }

switch(woodType){
    case 'A':
    case 'a': ftk = arraylocation[0][0]; fck = arraylocation[1][0];break;
    case 'B':
    case 'b': ftk = arraylocation[0][1]; fck = arraylocation[1][1];break;
    case 'C':
    case 'c': ftk = arraylocation[0][2]; fck = arraylocation[1][2];break;
    case 'D':
    case 'd': ftk = arraylocation[0][3]; fck = arraylocation[1][3];break;
    case 'E':
    case 'e': ftk = arraylocation[0][4]; fck = arraylocation[1][4];break;
    case 'F':
    case 'f': ftk = arraylocation[0][5]; fck = arraylocation[1][5];break;
    case 'G':
    case 'g': ftk = arraylocation[0][6]; fck = arraylocation[1][6];break;
    case 'H':
    case 'h': ftk = arraylocation[0][7]; fck = arraylocation[1][7];break;
    case 'I':
    case 'i': ftk = arraylocation[0][8]; fck = arraylocation[1][8];break;
    case 'J':
    case 'j': ftk = arraylocation[0][9]; fck = arraylocation[1][9];break;
    case 'K':
    case 'k': ftk = arraylocation[0][10]; fck = arraylocation[1][10];break;
    case 'L':
    case 'l': ftk = arraylocation[0][11]; fck = arraylocation[1][11];break;
    case 'M':
    case 'm': ftk = arraylocation[0][12]; fck = arraylocation[1][12];break;
    case 'N':
    case 'n': ftk = arraylocation[0][13]; fck = arraylocation[1][13];break;
    case 'O':
    case 'o': ftk = arraylocation[0][14]; fck = arraylocation[1][14];break;
    case 'P':
    case 'p': ftk = arraylocation[0][15]; fck = arraylocation[1][15];break;
    case 'Q':
    case 'q': ftk = arraylocation[0][16]; fck = arraylocation[1][16];break;
    case 'R':
    case 'r': ftk = arraylocation[0][17]; fck = arraylocation[1][17];break;
}

    cout <<"The ftk value is: "<< ftk<< endl<<"The fck value is: "<< fck<<endl;

    return ftk;
    return fck;

    myInfile.close();
}

2 个答案:

答案 0 :(得分:1)

for (row = 0; row<3; row++) //you have no open and close braces for this for loop

答案 1 :(得分:1)

建议:
1)查找std::toupperstd::tolower,这样您就不必在case语句中同时使用大写和小写字母。

2)通过减去字母来创建索引:

unsigned int index = std::toupper(woodType) - 'A';
ftk = arraylocation[0][index];
fck = arraylocation[1][index];

3)函数只能返回一个值:ftkfck。 如果要返回多个值,请通过引用传递它们或将它们放在结构中并返回已修改结构的副本。

4)return语句后没有执行流,因此您的代码永远不会执行第二个返回语句或fclose