C++ 复制int数组中的文件数据
我想问一下,我有一个文件,其中的数字是按行和列写的:C++ 复制int数组中的文件数据,c++,linux,C++,Linux,我想问一下,我有一个文件,其中的数字是按行和列写的: 23 54 433 65 23 44 3 32 422 43 我想在二维int数组中复制,但我不知道怎么做。我想应用一个字符串标记函数,但如何应用它我不知道该怎么做,请给我一点指导 谢谢这个问题有两个答案。其中之一非常简单,假设您知道所讨论的输入文件的列数和行数 for (int a=0; a<NUMROW; a++) for (int b=0; b<NUMCOL; b++) cin>>
23 54 433 65 23
44 3 32 422 43
我想在二维int数组中复制,但我不知道怎么做。我想应用一个字符串标记函数,但如何应用它我不知道该怎么做,请给我一点指导
谢谢这个问题有两个答案。其中之一非常简单,假设您知道所讨论的输入文件的列数和行数
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;
有人有没有不那么复杂的问题?请查看前面的问题:谢谢,先生,但我没有使用vector。还有其他方法吗?请帮助我您先前关于2D阵列的问题现在包含指向先前问题的URL链接,这些问题应该会对您有所帮助。我上面提到的问题涉及从文本文件读取int值。如果你希望有人能为你写代码,你可能是运气不好。你应该使用vector。向量可以用作int数组&v[0]与int[]或int*相同。