c++ - 将文件数据复制到 int 数组中

标签 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>>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; 

有人有更简单的东西吗?

关于c++ - 将文件数据复制到 int 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5793523/

相关文章:

python - 我可以在并行窗口中为当前也正在运行作业的同一台 guest 计算机执行 vagrant ssh 吗?会影响现在的工作吗?

c++ - 在 Linux 上用 C++ 移动文件的更快方法

c++ - OpenCV 未处理的异常错误

c++ - 未收到 UDP 广播流量

python - 将 pybind11 绑定(bind)标记为已弃用的最佳方法

linux - 分别对每个文件进行 GZip

c++ - MS Visual Studio Windows 中的 Release模式与 Debug模式

c++ - 为什么我不能在 Win32 中启用 unicode Edit 控件?

linux - 如何删除Linux中多个目录中存在的文件内容

linux - 如何从 shell 脚本安排 cron 作业