2017-05-09 1 views
1

私はテキストファイルから座標を読み取ります。たとえば、「0 50 100」となります。テキストファイルを文字列ベクトルに保持しています。私は0と50と100を別々にしたい。私は2つのスペースの間の文字列を取得し、それをstoiを使って整数に変換することができると思った。しかし、私は別々に2つのスペースの間の文字列を取得することができませんでした。私が試したことを分かち合いました。これは正しいとは知りません。私の解決策を見つけるのを助けてくれますか?2つのスペースの間の文字列をC++で取得する

サンプルテキスト入力:サルーン4 0 0 50 0 50 100 0〜100(4サルーン4点を有することを意味例:図4(X1、Y1)後の最初の2つの整数)

for (int j = 2; j < n * 2 + 2; j++){ 
      size_t pos = apartmentInfo[i].find(" "); 
      a = stoi(apartmentInfo[i].substr(pos + j+1,2)); 
      cout << "PLS" << a<<endl; 
     } 
+0

。 http://stackoverflow.com/questions/236129/split-a-string-in-c – jsn

+0

正規表現を参照してください! –

答えて

0

あなたテキストから整数を抽出するためにstd::istringstreamを使用することができます。

#include <sstream> 
#include <vector> 
#include <string> 
#include <iostream> 

int main() 
{ 
    std::string test = "0 50 100"; 
    std::istringstream iss(test); 

    // read in values into our vector 
    std::vector<int> values; 
    int oneValue; 
    while (iss >> oneValue) 
    values.push_back(oneValue); 

    // output results 
    for(auto& v : values) 
    std::cout << v << "\n"; 
} 

Live Example


編集:次に名前、番号、および読書整数:ストリームが既に必要な解析能力を有するよう

#include <sstream> 
#include <vector> 
#include <string> 
#include <iostream> 

int main() 
{ 
    std::string test = "Saloon 4 0 0 50 0 50 100 0 100"; 
    std::string name; 
    int num; 
    std::istringstream iss(test); 
    iss >> name; 
    iss >> num; 
    std::cout << "Name is " << name << ". Value is " << num << "\n"; 
    std::vector<int> values; 
    int oneValue; 
    while (iss >> oneValue) 
    values.push_back(oneValue); 
    std::cout << "The values in vector are:\n"; 
    for(auto& v : values) 
    std::cout << v << " "; 
} 

Live Example 2

+0

たとえば、 "Saloon 4 0 0 50 0 50 100 0 100"でこのメソッドをどのように適用できますか?サルーンは整数ではないため、問題が発生します。 :/ – codelife

+0

最初の文字列を抽出し、ループを使用して整数を抽出します – Fureeish

+0

sstreamについて何も知らなかったので、非常に便利です!手伝ってくれてどうもありがとう! – codelife

0

解析番号std::ifstreamようなストリーム入力からは、通常の場合には容易です。

など。あなたはx、y座標を含む集約クラスcoordがあるとしましょう

std::ifstream in{"my_file.txt"}; 
int number; 
in >> number; // Read a token from the stream and parse it to 'int'. 

:ファイル入力ストリームからintを解析する、。

struct coord { 
    int x, y; 
}; 

カスタム追加入力ストリームから、それに解析するとき、それは、同時に、xとyの値の両方を読むことができるようにクラスcoordのための行動を解析することができます。

std::istream& operator>>(std::istream& in, coord& c) { 
    return in >> c.x >> c.y; // Read two times consecutively from the stream. 
} 

ストリームを使用する標準ライブラリのすべてのツールで、coordオブジェクトを解析できます。 など。

std::string type; 
int nbr_coords; 
std::vector<coord> coords; 

if (in >> type >> nbr_coords) { 
    std::copy_n(std::istream_iterator<coord>{in}, nbr_coords, std::back_inserter(coords)); 
} 

これは、ベクター中のxおよびy座標の両方を含む各coordオブジェクトをcoordオブジェクトの正しい数を読み取り、解析します。あなたのテキストが役立つかもしれSpliting

Live example

Extended live example

関連する問題