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 座標です。必要なのは、読みやすいデータ型で数値を抽出し、行列のようにアクセスできるようにすることだけです。[142, 310, 0, 959]、[299, 467, 0, 959]... というように 4 行の 4 つのコンテナーとして格納する必要があります。

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;

これら 4 つの値を行列のようなデータ構造にするにはどうすればよいでしょうか? まず、適切なスコープと有効期間でこれを宣言します。

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 に答える