2017-05-09 6 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))

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

텍스트가 도움이 될 수 Spliting. 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"에서이 방법을 어떻게 적용 할 수 있습니까? Saloon은 정수가 아니기 때문에 문제가있을 것입니다. :/ – 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; 
}; 

사용자 지정 부가 입력 스트림으로부터 그것에 파싱 때, 동시에 X 및 Y 값을 모두 판독 할 수 있도록 coord 클래스에 대한 동작을 분석 할 수있다. coord 개체를 구문 분석 할 수 스트림을 사용하는 표준 라이브러리에서

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

이제 모든 도구를 제공합니다. 예. :

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