2013-08-26 2 views
0

저는 여러 곳에서이를 검색하여 YouTube의 "TheNewBoston"C++ 가이드 전체를 살펴 봤지만 이에 대한 답을 아직 찾지 못했습니다.여러 변수가 포함 된 문자열 또는 함수 (C++)

저는 C++ 기술을 배우기위한 프로그램을 작성하고 있습니다. 여전히 멍청한데, 가능한 방법이라고 생각합니다.

내가하려고하는 프로그램은 체육관에서 훈련 할 때 특정 운동을 위해 얼마나 많은 담당자를 기록하는지입니다.

#include <iostream> 
#include <cstdlib> 
#include <string> 

using namespace std; 

int main() 
{ 
    string biceps = "biceps"; 
    string triceps = "triceps"; 
    string quads = "quads"; 
    string muscleChoice; 

    cout << "Welcome to MyPT!" << endl; 
    cout << endl; 
    cout << "What are you going to be training today?" << endl; 
    cout << endl; 
    cout << "**Biceps** \n\n**Triceps** \n\n**Quads**" << endl; 
    cout << endl; 
    cin >> muscleChoice; 
    if ((muscleChoice == "biceps") || (muscleChoice == "triceps") || (muscleChoice == "quads")) 
    { 
     cout << "working" << endl; 
    } 



    return 0; 
} 

그건 본질적으로 내가 원하는 것입니다. 그러나 분명히 내가 더 많은 가능성을 가지고 있다면 그것은 지저분해질 수 있습니다. 내가 원한 것은 이런 모습이다.

cin >> muscleChoice; 

if (muscleChoice == oneFunctionThatIncludesAllThoseStrings) 
{ 
    cout << "working" 
} 

아무도 그렇게하는 방법을 알고 않습니다 (물론 기능은 더 잘 설명하려고 이렇게 오래되지 않을 것)?

(내가 이해하지 않을 수 있습니다으로 내가 멍청한 놈 해요, 당신의 대답을 설명해주십시오)

+0

당신은 ::'표준을 의미 '과'를 설정합니다.find()'호출? – WhozCraig

+1

예 고맙습니다. – Nvarano

답변

4

당신은 운동 문자열의 std::set 사용하고 입력 문자열이 그 집합의 구성원인지 확인할 수 있습니다 :

01 : 당신이 담당자의 집계를 유지하려면
std::set<std::string> exercises{"biceps", "triceps", "quads"}; 

다음

if (exercises.find(muscleChoice) != exercises.end()) 
{ 
    std::cout << "working"; 
} 

, 당신은 std::map 대신 사용할 수

std::map<std::string, unsigned int> exercises; 

if (exercises.find(muscleChoice) != exercises.end()) 
{ 
    std::cout << "working"; 
    exercises[muscleChoice]++; // increase count for this muscle choice 
} 
+0

예 감사합니다! 이것은 내가 원했던 것이다. – Nvarano

+0

#를 포함해야합니까? 'set'은 'std'의 멤버가 아닙니다. – Nvarano

+0

@ user2716905 예,'std :: set'은''이고'std :: map'은''입니다. 필요한 헤더를 알려주는 참조 링크를 추가했습니다. – juanchopanza

0

첫 번째로 할 일은 배열에서 동일성을 테스트하려는 모든 문자열과 배열을 반복하고 평등을 검사하는 함수를 갖는 것입니다. 사용에 관해서는

bool testForEquality(string s){ 
    for(int i=0; i<3; i++){ 
     if(s == commands[i]) return true; 
    } 

    return false; 
} 

:

cin >> muscleChoice; 

if (testForEquality(muscleChoice)) 
{ 
    cout << "working" 
} 
0

내가 그런 식으로했다 : 그런 다음

string commands[] = { "bicep", "tricep", "quad" }; 

은 평등을 확인하는 당신이 원하는 무엇

#include <iostream> 
#include <cstdlib> 
#include <string> 

#include <algorithm> // find function 
#include <vector> // dynamic array to store choices 

using namespace std; 

int main() 
{ 
    vector<string> accepted_choices; 
    accepted_choices.push_back("biceps"); // add a choice 
    accepted_choices.push_back("tricep"); 
    accepted_choices.push_back("quad"); 

    cout << "Welcome to MyPT!" << endl; 
    cout << endl; 
    cout << "What are you going to be training today?" << endl; 
    cout << endl; 
    cout << "**Biceps** \n\n**Triceps** \n\n**Quads**" << endl; 
    cout << endl; 
    cin >> muscleChoice; 
    if (find(accepted_choices.begin(), accepted_choices.end(), muscleChoice) != accepted_choices.end()) // find returns container.end() if it failed to find 
    { 
     cout << "working" << endl; 
    } 



    return 0; 
} 
0

단순히 선택 목록을 사용하고 if를 사용하여 그 중 하나를 선택합니다. tatement. 옵션은 다음과 같은 문자열 배열에 다른 선택 항목을 할당하는 것입니다.

string Body_Parts[3] = { "biceps", "triceps", "quads" }; 

및 이점을 이용하십시오.

for(int i=0; i<3; i++) {  
     if(muscleChoice==Body_Parts[i]) 
      cout<<"working"<<endl; 
    } 

코드의 조각

위에서 당신은 모든 선택의 배열에 int 형의 muscleChoice를 비교하고 당신이 그것을 일치하는 항목을 발견하면 원하는대로 출력한다.

+0

이것은 또한 당신에게 감사합니다 :) – Nvarano

0

C++ 98 솔루션 :

string muscles[3] = { "biceps", "triceps", "quads" } ; 
vector<string> vec(muscles, muscles+3); 
set<string> muscles_set(vec.begin(), vec.end()); 

if (muscles_set.count(muscleChoice)) 
관련 문제