2017-04-05 1 views
1

string 입력을 두 개의 다른 int으로 어떻게 분할합니까?두 개의 int 로의 C++ 분할 문자열 입력

나는 입력에 두 개의 서로 다른 분수를 (같은 2/3) 프로그램을 쓰고 있어요 및 문자열로 2/3에 읽고 싶은와 구분합니다 (/)하여 분할하고있다.

예 :

Input: 2/3 
Values: 
int num = 2; 
int denom = 3; 

예 2 :

Input: 11/5 
Values: 
int num = 11; 
int denom = 5; 

감사합니다! "2/3"와 같은 매우 간단 뭔가를

+0

잘 할 수 있습니다 : http://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c to 문자열을 분할하면 http://stackoverflow.com/questions/194465/how-to-parse-a-string-to-an-int-in-c 문자열을 int로 변환 할 수 있습니다. – Eddge

+0

간단한 작업을 위해서'int a, b; char c; std :: cin >> a >> c >> b;' – Logman

+0

''cin' 대신에'stringstream' 객체를 사용할 수 있다는 것을 잊어 버렸습니다. – Logman

답변

1

당신은 '/'문자가있는 것을 당신의 문자열의 위치를 ​​반환합니다 string.find

string.findstring.substr를 사용할 수 있습니다. 그런 다음 string.substr을 사용하여 '/'문자 앞뒤에 문자열을 분할 할 수 있습니다. 코드 예제를 작성할 시간이 없지만, 정말로 붙어 있다면 오후에 내가 집에 올 때 뭔가 노크 할 것입니다.

0

g ++를 사용하는 경우 -std = C++ 11 플래그를 지정하여 다음을 실행하십시오.

#include <iostream> 
#include <string> 

void find_num_denom(int& num, int& denom, std::string input) { 
    int slash_index = input.find("/"); 
    num = std::stoi(input.substr(0, slash_index)); 
    denom = std::stoi(input.substr(slash_index + 1, input.length())); 
} 

int main() { 
    int n,d; 
    find_num_denom(n, d, "23/52"); 
    std::cout<<n<<" "<<d<<"\n"; 
    return 0; 
} 

이것은 2352를 반환합니다. 어떤 문제가 있으면 알려주세요