2014-03-30 3 views
0

이 가능합니다. 계산을하려고하면 기본 변수 유형이 int 일 수 있습니다.하지만 프로그램의 일부로 while 루프를 수행하고 if 문을 기존의 목적으로 throw하기로 결정했습니다. 하나 CIN이 >> 그리고 그 계산을 실행할 수에 걸릴 것입니다,하지만 그들은 종료 할 넣다 당신은 또한 입력이 필요합니다 여기 어떻게하면 입력을 문자열과 int로 만들 수 있습니까? C++

#include <iostream> 

using namespace std; 


int func1(int x) 
{ 
    int sum = 0; 
    sum = x * x * x; 
    return sum; 
} 

int main() 
{ 
    bool repeat = true; 

    cout << "Enter a value to cube: " << endl; 
    cout << "Type leave to quit" << endl; 

    while (repeat) 
    { 
     int input = 0; 
     cin >> input; 
     cout << input << " cubed is: " << func1(input) << endl; 

     if (input = "leave" || input = "Leave") 
     { 
      repeat = false; 
     } 

    } 
} 

나 '와 함께 작동하도록 일부 코드입니다 그들이 원인을 입력 int로 설정되어 떠나지 않을 알고 있지만 변환 또는 뭔가를 사용할 수 있습니다 ...

다른 건 거기에 더 좋은 방법은 루프를 깰 수있는 가장 일반적인 방법은 무엇입니까?

+2

왜 '동안 (사실)'와'break'처럼 사용할 수 있습니까? –

답변

2

입력 스트림에서 입력을 문자열로 읽을 수 있습니다. ..이 경우 '떠나'와 종료 확인하고 숫자로 변환하고 FUNC1 전화 .. atoi 함수 보거나 높일 :: 또한 <>

lexical_cast하지 않은 경우는 input == "leave"==가 동일하다 운영자. =은 대입 연산자입니다. 이 작업을 수행하는

int main() { 
    cout << "Enter a value to cube: " << endl; 
    cout << "Type leave to quit" << endl; 

    while (true) 
    { 
     string input; 
     cin >> input; 

     if (input == "leave" || input == "Leave") 
     { 
      break; 
     } 
     cout << input << " cubed is: " << func1(atoi(input.c_str())) << endl; 

    } 
} 
+0

atoi 함수는 "abc"또는 "abc123"과 같은 영문자 문자열을 전달할 경우 잘못된 int 데이터를 반환 할 수 있습니다. – rajenpandit

3

한 가지 방법은 cin에서 문자열을 읽습니다. 그 값을 확인하십시오. 종료 조건을 만족하면 종료하십시오. 그렇지 않으면, 문자열에서 정수를 추출하고 정수를 procss로 진행하십시오.

while (repeat) 
{ 
    string input; 
    cin >> input; 
    if (input == "leave" || input == "Leave") 
    { 
     repeat = false; 
    } 
    else 
    { 
     int intInput = atoi(input.c_str()); 
     cout << input << " cubed is: " << func1(intInput) << endl; 
    } 
} 
2

당신이

int input; 
string s; 
cint>>s; //read string from user 
stringstream ss(s); 
ss>>input; //try to convert to an int 
if(ss==0)  //not an integer 
{ 
     if(s == "leave") {//user don't want to enter further input 
      //exit 
     } 
     else 
     { 
       //invalid data some string other than leave and not an integer 
     } 
} 
else 
{ 
     cout<<"Input:"<<input<<endl; 
      //input holds an int data 

} 
관련 문제