2014-09-26 3 views
0

Microsoft Visual Studio C++에서이 코드를 실행하려고하면 오류가 발생합니다. 그것은 실행되지만 출력되는 비용의 가치는 잘못되었습니다. 왜 그런가요? 나는 기본 문을 포함하고 있지 않다는 것을 깨닫고 cost을 두 번 선언하고있다. 이것은 cost에 선언 된 값이 없으므로 디버그 오류가 발생하므로 스위치 문이 처리 중이 지 않은 것으로 간주된다. 일부는 어떻게 이해하지 못합니까?
cout << "Pizza"; 어떻게 수정합니까?Switch 문이 비용 값을 잘못 입력했습니다.

#include "stdafx.h" 
#include <iostream> 
#include <iomanip> 
#include <cmath> 
#include <cstdlib> 
#include <time.h> 
#include <Windows.h> 
#include <string> 

using namespace std; 

int main() 
{ 
    int a, b, c, d, e, f, m, p, k, User_Input, Pizza , cost; 
    a = 0; 
    b = 0; 
    c = 0; 
    d = 0; 
    e = 0; 
    f = 0; 
    k = 0; 
    cost = 0; 

    cout << "What is your favorite vegetarian food from the list below?" << endl; 
    Sleep(1500); 
    cout << "Pizza\n"; 
    Sleep(200); 
    cout << "IceCream\n"; 

    cin >> User_Input; 
    switch (User_Input) 
    { 
    case 1: 
     cout << "Pizza"; 
     cost = 5; 
     break; 
    case 2: 
     cout << "IceCream"; 
     cost = 5; 
     break; 

    } 


    Sleep(2000); 
    cout << "The total cost will be: " << cost; 
    cout << "\n\n\n\t\t\t"; 

    return 0; 


} 
+0

잘못된 값을 출력한다고 말하면 올바른 값은 무엇이라고 생각하십니까? – jonynz

+0

잘못된 값으로 표시하면 아무 것도 출력하지 않는다는 의미입니까? –

+0

메시지를 입력 할 때 프로그램에 입력 한 내용과 "잘못된 값을 제공합니다"라는 말 대신에 결과로 실제로 얻은 가치를 말하면 편리 할 것입니다. 그런데 두 경우 모두 '비용'을 '5'로 설정합니다. – lurker

답변

2

User_Input은 "int"유형이며, cin을 통해 해당 변수에 문자열을 읽으려고하면 예기치 않은 결과가 나타납니다. 당신이 아마하고 싶은 중 하나입니다

  • 문자열로 읽고 switch 문

단순화를 문자열로 읽어 문자열 비교

  • 을 int로 변환하고, 할 예 :

    #include <iostream> 
    #include <string> 
    int main() 
    { 
         std::string user_input; 
         int cost = 0; 
         std::cout << "What is your favorite vegetarian food from the list below?\nPizza\nIceCream\n"; 
         std::cin >> user_input; 
         if(user_input == "Pizza") { 
           cost = 5; 
         } else if (user_input == "IceCream") { 
           cost = 10; 
         } 
         std::cout << "The total cost will be: " << cost << std::endl; 
         return 0; 
    } 
    
  • +0

    내가 upvoted. 나는 당신이 제안한 고급 옵션 # 2를 선호합니다. 과거 C 프로그램에서 나는 DJB2와 같은 해쉬 함수를 사용했다. –

    관련 문제