0

私はこのようなテキストファイルを持っています

Path 
827 196
847 195
868 194
889 193
909 191
929 191
951 189
971 186
991 185
1012 185
Path
918 221
927 241
931 261
931 281
930 301
931 321
927 341
923 361
921 382

getline関数を使用してテキストファイルのすべての行を読み取っています。1行の2つの数値を2つの異なる整数変数に解析したいと思います。これまでのコードはです。

int main()
{

  vector<string> text_file;

  int no_of_paths=0;

  ifstream ifs( "ges_t.txt" );
  string temp;

  while( getline( ifs, temp ) )
  {
          if (temp2.compare("path") != 0)
          {
//Strip temp string and separate the values into integers here.
          }

  }


}
4

3 に答える 3

2
int a, b;
stringstream ss(temp);
ss >> a >> b;
于 2012-09-04T09:40:13.643 に答える
1

2つの整数を持つ文字列が与えられた場合:

std::istringstream src( temp );
src >> int1 >> int2 >> std::ws;
if ( ! src || src.get() != EOF ) {
    //  Format error...
}

"path"同様に比較する前に空白をトリミングしたい場合があることに注意してください 。(空白の追跡は、通常のエディターでは表示されないため、特に有害な場合があります。)

于 2012-09-04T09:58:32.930 に答える
1

このようなもの:

#include <string>
#include <sstream>
#include <fstream>

std::ifstream ifs("ges_t.txt");

for (std::string line; std::getline(ifs, line); )
{
    if (line == "Path") { continue; }

    std::istringstream iss(line);
    int a, b;

    if (!(iss >> a >> b) || iss.get() != EOF) { /* error! die? */ }

    std::cout << "You said, " << a << ", " << b << ".\n";
}
于 2012-09-04T09:39:36.810 に答える