2

这是我写的不完整的代码。

string line; 
ifstream fp ("foo.txt"); 
if (fp.fail()){
    printf("Error opening file %s\n", "foo.txt");
    return EXIT_FAILURE; 
}

unsigned int lineCounter(1); 
while(getline(fp, line)){
    if(lineCounter == 1){
        lineCounter++;
    } // to skip first line
    else{
        // find and extract numbers
    } 
}

foo.txt 文件如下所示。

x0,x1,y0,y1
142,310,0,959
299,467,0,959
456,639,0,959
628,796,0,959

基本上,数字是 x 和 y 坐标。我需要的只是以易于阅读的数据类型提取数字,并且能够像矩阵一样访问它们。它应该存储为 4 个容器,4 行具有 [142, 310, 0, 959], [299, 467, 0, 959]...等等。

我尝试了 find() 函数,但我不确定如何正确使用它来将它们放入数据类型中。

如何仅提取数字并将它们存储在可以移动并像数组一样访问它们的数据类型中?

4

2 回答 2

2

要读取用逗号分隔的 4 个数字,请执行此操作;

std::string line;
std::getline(file, line);

std::stringstream linestream(line);

int  a,b,c,d;
char sep; // For the comma

// This should work even if there are spaces in the file.
// The operator >> will drop leading white space
// Then read the next type
//      For int object will read an integer from the stream
//      For char object will read the next char (after dropping leading white space)
linestream >> a >> sep >> b >> sep >> c >> sep >> d;
于 2011-03-10T20:07:16.320 回答
1

基于@Martin 的回答:

std::string line;
std::getline(file, line);

std::stringstream linestream(line);

int  a,b,c,d;
char sep; // For the comma

// This should work even if there are spaces in the file.
// The operator >> will drop leading white space
// Then read the next type
//      For int object will read an integer from the stream
//      For char object will read the next char (after dropping leading white space)
linestream >> a >> sep >> b >> sep >> c >> sep >> d;

我们如何将这四个值放入类似矩阵的数据结构中?首先,在具有适当范围和生命周期的地方声明它:

std::vector< std::vector<int> > matrix; // to hold everything.

接下来,将此代码添加到您的行阅读循环中:

{
    std::vector <int> vi;
    vi.push_back(a);
    vi.push_back(b);
    vi.push_back(c);
    vi.push_back(d);
    matrix.push_back(vi);
}

最后,在分析矩阵的代码中:

int item;
item = matrix[0][0] + matrix[1][1] + matrix[2][2]; // for example.
于 2011-03-10T20:30:55.687 回答