2017-05-09 79 views
1

我正在讀取文本文件中的座標。例如「0 50 100」。我將我的文本文件保存在一個字符串向量中。我想得到0和50和100分開。我認爲我可以使它成爲2個空格之間的字符串,然後使用stoi將其轉換爲整數。但我無法單獨在兩個空間之間獲得一個字符串。我分享了我嘗試過的。我知道這是不正確的。你能幫我找到我的解決方案嗎?在C++中獲取2個空格之間的字符串

樣本文本輸入:轎車4 0 0 50 0 50 100 0 100(4表示轎車有4點實施例:首先的兩個整後4示出了(X1,Y1))

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從輸入流這樣很容易在正常的情況下,作爲流已經具備必要的分析能力。

例如,從文件輸入流解析int

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

假設你有一個聚合類coord含有X和Y座標。

struct coord { 
    int x, y; 
}; 

您可以添加自定義的類coord解析行爲,以便它可以在同一時間讀取x和y的值,從輸入流解析成它的時候。

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)); 
} 

這將讀取和解析對象coord的正確數量到載體中,同時含有的x和y座標的每個coord對象。

Live example

Extended live example

相關問題