我使用Windows 7上的Code::Blocks从.cpp文件中提取很少的.exe,我是一个初学者(对不起!)

这是今天的问题:

我有一个.csv文件,其中包含长整数(从0到2 ^ 16),中间用分号隔开,并列为一系列水平线。

我将在这里做一个简单的例子,但实际上文件最多可以达到2Go。

假设我的文件wall.csv在像Notepad++这样的文本编辑器中显示为:

350;3240;2292;33364;3206;266;290

362;314;244;2726;24342;2362;310

392;326;248;2546;2438;228;314

378;334;274;2842;308;3232;356

奇怪的是,它在Windows notepad中看起来像这样
350;3240;2292;33364;3206;266;290
362;314;244;2726;24342;2362;310
392;326;248;2546;2438;228;314
378;334;274;2842;308;3232;356

无论如何,

假设我将知道并在3个float变量中声明列数,行数和文件中的值。
int col = 7;   // amount of columns
int lines = 4; // amount of lines
float x = 0;     // a variable that will contain a value from the file

我想要的:
  • 创建一个vector <float> myValues
  • 用CSV的第一行第1行中的每个值myValues.push_back(x)
  • 用csv
  • 的第二行的每个值执行myValues.push_back(x)
  • 第三行中的每个值...等执行myValues.push_back(x)

  • 直到文件已完全存储在 vector myValues中。

    我的问题:

    我不知道如何将CSV文件中存在的值依次分配给x

    我该怎么办?

    好的,此代码可以正常工作(虽然很慢,但是还可以!):
    #include <iostream>
    #include <fstream>
    #include <vector>
    using namespace std;
    
    int col = 1221;   // amount of columns
    int lines = 914; // amount of lines
    int x = 0;     // a variable that will contain a value from the file
    
    vector <int> myValues;
    
    int main() {
    
        ifstream ifs ("walls.tif.csv");
    
        char dummy;
        for (int i = 0; i < lines; ++i){
            for (int i = 0; i < col; ++i){
                ifs >> x;
                myValues.push_back(x);
                // So the dummy won't eat digits
                if (i < (col - 1))
                    ifs >> dummy;
            }
        }
        float A = 0;
        float B = col*lines;
    
        for (size_t i = 0; i < myValues.size(); ++i){
    
            float C = 100*(A/B);
            A++;
            // display progress and successive x values
            cout << C << "% accomplished, pix = " << myValues[i] <<endl;
        }
    }
    

    最佳答案

    尝试使用C++标准模板库的输入操作。

    创建一个虚拟字符变量以吃掉分号,然后将cin数输入x变量中,如下所示:

    char dummy;
    for (int i = 0; i < lines; ++i){
        for (int i = 0; i < col; ++i){
            cin >> x;
            myValues.push_back(x);
            // So the dummy won't eat digits
            if (i < (col - 1))
                cin >> dummy;
        }
    }
    

    为此,您可以将csv文件重定向为从命令行输入,如下所示:
    yourExecutable.exe < yourFile.csv
    

    要遍历充满数据的 vector :
    for (size_t i = 0; i < myVector.size(); ++i){
        cout << myVector[i];
    }
    

    上面的size_t类型由STL库定义,用于抑制错误。

    如果您只想使用一次值,并在使用时将其从容器中删除,那么最好使用std::queue容器。这样,您可以使用front()查看front元素,然后使用pop()删除它。

    10-07 19:52
    查看更多