复制int数组中的文件数据

时间:2011-04-26 16:40:50

标签: c++ linux

我想问一下,我有一个文件,其中的行以列和列编写:

23 54 433 65 23 
44 3  32  422 43

我想在二维int数组中复制,但我不知道该怎么做。我想应用一个字符串令牌功能,但如何应用它我不知道该做些什么,请指导我一点点

感谢

1 个答案:

答案 0 :(得分:0)

这个问题有两个答案。其中一个非常简单(假设你知道输入文件的列数和行数)。

for (int a=0; a<NUMROW; a++)
    for (int b=0; b<NUMCOL; b++)
        cin>>TWODARRAY[a][b];

所以这很容易。对于可变长度的数据输入,我提出的漫长而笨拙的答案更令人兴奋。不过,我已经测试了它,它确实有效。希望每个人都对指针和字符串流的指针感到满意。

string in;
int** twoDArray=NULL;
int numRow=0;
int numCol=0;
string** inputHold=NULL;
int inputSize=10;
//Since we're using pointers instead of vectors, 
    //we have to keep track of the end of the array.
inputHold=new string*[inputSize]; 
while (getline(cin,in)){
    //The string in now contains a line of input.
    if (numRow==0)
    //Assuming that the number of inputs per column is the same in each row,
            //we can save on computation by only checking the number of columns once.
    //Performance may be improved here- it might be more efficient to use str.find
        for (string::iterator iter=in.begin(); iter!=in.end(); iter++){
            if (*iter==' ')
                numCol++;
        }
    //Store the string
    inputHold[numRow]=new string(in);

    numRow++;
    if (numRow==inputSize) {
        //If we're at the end of the array, we create a bigger one and repopulate the data.
        string** tmpInput=inputHold;
        int oldsize=inputSize;
        inputSize=inputSize*2;
        inputHold=new string*[inputSize];
        for (int i=0; i<oldsize; i++){
            inputHold[i]=tmpInput[i];
        }
    }
}
//The method that I used to determine the number of columns is mildly flawed-
    //it doesn't account for the end of line.  So, we increment the counter.
numCol=numCol+1;
twoDArray=new int*[numRow];
for (int a=0; a<numRow; a++)
    twoDArray[a]=new int[numCol];
for (int a=0; a<numRow; a++){
    istringstream parser(*(inputHold[a]));
    for (int b=0; b<numCol; b++){
        parser>>twoDArray[a][b];
    }
}

for (int a=0; a<numRow; a++)
    for (int b=0; b<numCol; b++)
        cout<<twoDArray[a][b]<<endl; 

任何人都不那么复杂了吗?