2

私はいくつかのファイルで作業していて、それらを読み込もうとしていました。ベクトルを使用して最終的な情報を保存したかったので、その大きさを知る必要なくグローバルに保持できます。これは私のコードですが、プログラムの起動が完了しません:

std::string one = "v 100.32 12321.232 3232.6542";
struct Face {float x, y, z;};
std::vector<struct Face> obj;
char space[3];
sscanf(one.c_str(), "%s %f %f %f", space, &obj[1].x1, &obj[1].y1, &obj[1].z1);
std::cout << obj[1].x1 << std::endl;
4

3 に答える 3

3

デフォルトで構築されたvectors は空で開始され、コンパイラで を使用できますがoperator []、これは未定義の動作です。

vectorただし、作成時にスペースを割り当てることができます。

std::vector<struct Face> obj(2); // Allow enough space to access obj[1]

于 2012-12-28T19:41:59.983 に答える
2

ベクトルの要素 1 に書き込みたい場合、ベクトルにはsize() >= 2. あなたの例でsize()は、常に0です。

一時的な を作成し、Faceそれを にpush_back-ing することを検討してくださいvector<Face>

于 2012-12-28T19:40:35.993 に答える
1

正当な理由でsscanfを使用している可能性がありますが、少なくとも、ストリームを使用して情報を構造体にロードできることを指摘するのは良いことだと思います。

この場合、istringstreamクラスを使用することをお勧めします。これにより、値を文字列から値として読み取り、必要に応じてキャストできます。だから、あなたのコード、私はそれをこれに変えることができると思います:

std::string one = "v 100.32 12321.232 3232.6542";
struct Face {float x,y,z;};
std::vector<struct Face>obj;
char space[3];

// As mentioned previously, create a temporal Face variable to load the info
struct Face tmp; // The "struct" maybe can be omited, I prefer to place it.

// Create istringstream, giving it the "one" variable as buffer for read.
istringstream iss ( one );

// Replace this line...
//sscanf(one.c_str(), "%s %f %f %f",space,&obj[1].x1,&obj[1].y1,&obj[1].z1);
// With this:
iss >> space >> tmp.x >> tmp.y >> tmp.z;

// Add the temporal Face into the vector
obj.push_back ( tmp );

// As mentioned above, the first element in a vector is zero, not one
std::cout << obj[0].x1 << std::endl;

この場合、文字列からロードする値がある場合、istringstreamクラス(「sstream」を含める必要があります)が役立ちます。

私の答えが何らかの形であなたを助けることを願っています。

于 2012-12-28T20:42:56.553 に答える