2013-09-07 4 views
0

Я новичок в C++. Моя первая цель - сделать успешную программу калькулятора консольным приложением Win32, но я все время получаю сообщение об ошибке. Я положил этот код:У меня проблемы с моим калькулятором

cout << "Do you want to continue? N/Y" << endl; 
cin >> ny; 

if (ny == "Y") goto start; 
if (ny == "N") goto end; 

Но он продолжает идти в любом случае.

Это код «конец»:

// End - Properties 
system("cls"); 
system("title Basic Calculator - End"); 
system("color 4F"); 

// End - Start 
ny == "0"; 
cout << "Are you sure you want to end? N/Y" << endl; 
cin >> ny; 

if (ny == "N") goto start; 

cin.get(); 

return 0(); 

И в конце концов, это также всегда заканчивает программу.

Если вы обнаружили ошибку, пожалуйста, дайте мне знать.

-Danish Humair

Полный код:

#include <iostream> 

using namespace std; 

int main() 
{ 
start: 
    // Program - Properties 
    system("cls"); 
    system("title Basic Calculator - Main Screen"); 
    system("color 1F"); 

    // Program - Setup 
    int input; 
    int x; 
    int y; 
    char ny [10]; 

    // Program - Start 
    cout << "Please choose an operation from the following." << endl << endl; 
    cout << "1. Addition \n2. Subtraction \n3. Multiplication \n4. Division" <<endl << endl; 
    cin >> input; 
    if (input = 1) goto addition; 
    if (input = 2) goto subtraction; 
    if (input = 3) goto multiplication; 
    if (input = 4) goto division; 
    cin.get(); 

addition: 

    // Addition - Properties 
    system("cls"); 
    system("title Basic Calculator - Addition"); 
    system("color 2F"); 

    // Addition - Start 
    cout << "Please input your first number." << endl; 
    cin >> x; 
    cout <<endl << "Please input your second number."<< endl << endl; 
    cin >> y; 
    cout <<endl <<endl << "The answer is " << x+y << ".\a" << endl << endl; 
    cout << "Do you want to continue? N/Y" << endl; 
    cin >> ny; 

    if (ny == "Y") goto start; 
    if (ny == "N") goto end; 

    cin.get(); 

subtraction: 

multiplication: 

division: 

end: 
    // End - Properties 
    system("cls"); 
    system("title Basic Calculator - End"); 
    system("color 4F"); 

    // End - Start 
    ny == "0"; 
    cout << "Are you sure you want to end? N/Y" << endl; 
    cin >> ny; 

    if (ny == "N") goto start; 

    cin.get(); 

    return 0(); 
} 
+4

Вы определенно должны заменить эти 'goto's. – chris

+2

и разместите свои ошибки – billz

+0

У меня только что было общее воспоминание Apple BASIC. – WhozCraig

ответ

4

Несколько вопросов должны быть решены.

1) Объявление ny как std::string ny; Вам нужно будет добавить #include <string>. Это позволит избежать переполнения буфера.

2) Как уже упоминалось ранее, вам необходимо изменить свои операторы if.

if (input == 1) goto addition; // Use '==' for comparison 
if (input == 2) goto subtraction; 
if (input == 3) goto multiplication; 
if (input == 4) goto division;  

3) Убедитесь, что вы проверить в нижнем регистре у и п

if (ny[0] == 'Y' || ny[0] == 'y') goto start; // notice the single quotes 
if (ny[0] == 'N' || ny[0] == 'n') goto end; 

// ... 
// Also change the following 
ny[0] = '\0'; // Not really necessary since you assign it immediately after 
// ... 
if (ny[0] == 'N' | ny[0] == 'n') 

4) Ваше return утверждение неверно. Измените его на:

return 0; // Doesn't need parenthesis 

Как профессиональный программист я должен предложить вам не использовать GOTO заявления и инкапсулировать свои алгоритмы функций. Ниже приведен пример, основанный на вашем исходном коде. FYI, я проверить компилирует на Visual Studio 2010 Professional

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 

// Forward declarations 
void addition(); 
void subtraction(); 
void multiplication(); 
void division(); 

int main() 
{ 
    bool again = true; 

    // Program - Setup 
    int input; 
    std::string ny; 

    while(again) 
    { 
     // Program - Properties 
     system("cls"); 
     system("title Basic Calculator - Main Screen"); 
     system("color 1F"); 

     // Program - Start 
     cout << "Please choose an operation from the following." << endl << endl; 
     cout << "1. Addition \n2. Subtraction \n3. Multiplication \n4. Division" <<endl << endl; 
     cin >> input; 
     cin.get(); 

     if (input == 1) {addition();} 
     else if (input == 2) {subtraction();} 
     else if (input == 3) {multiplication();} 
     else if (input == 4) {division();} 
     else 
     { 
      cout << "Invalid input\n"; 
      again = false; 
     } 

     cout << "Do you want to continue? N/Y" << endl; 
     cin >> ny; 
     cin.get(); 

     if (ny[0] == 'Y' || ny[0] == 'y') 
     { 
      again = true;  
     } 
     else 
     { 
      // Ask if they are sure 
      system("cls"); 
      system("title Basic Calculator - End"); 
      system("color 4F"); 

      cout << "Are you sure you want to end? N/Y" << endl; 
      cin >> ny; 
      cin.get(); 

      if (ny[0] == 'Y' || ny[0] == 'y') 
      { 
       again = false; 
      } 
      else 
      { 
       again = true; 
      } 
     } 
    } 

    return 0; 
} 

void addition() 
{ 
    int x; 
    int y; 
    // Addition - Properties 
    system("cls"); 
    system("title Basic Calculator - Addition"); 
    system("color 2F"); 

    // Addition - Start 
    cout << "Please input your first number." << endl; 
    cin >> x; 
    cout <<endl << "Please input your second number."<< endl << endl; 
    cin >> y; 
    cout <<endl <<endl << "The answer is " << x+y << ".\a" << endl << endl; 
} 

void subtraction() 
{ 

} 

void multiplication() 
{ 

} 

void division() 
{ 

} 
+0

: | Все еще не работает. Возможно, это что-то с моим компилятором «Visual Studio 2010 Ultimate». –

+0

@DanishHumair: Попробуйте [ideone.com] (http://ideone.com/), чтобы убедиться. – Jamal

+0

Я неправильно использовал символ для cin. Я обновил свое решение, чтобы использовать std :: string, что позволит избежать переполнения буфера. – jmstoker

3

если (вход = 1) Гото добавление

Я думаю, вы должны проверить (вход == 1), но вы назначаете его вход (вход = 1).

Кодекс должен быть: -

if (input == 1) goto addition; 
if (input == 2) goto subtraction; 
if (input == 3) goto multiplication; 
if (input == 4) goto division; 
+0

Gautam, те утверждения if не являются символами, они являются целыми числами. Хотя, спасибо за ваш ответ. Я попробовал, но все еще не работал ... - Датский Humair –

1

Я сделал несколько изменений, 1) Заявленный пу, как символ вместо массива. 2) Проверка как небольших, так и заглавных букв.

Я добавил комментарии, где бы я ни делал изменения. Надеюсь, это поможет.

// #include "stdafx.h" //If you get error include this 
    #include <iostream> 

    using namespace std; 

    int main() 
    { 
    start: 
     // Program - Properties 
     system("cls"); 
     system("title Basic Calculator - Main Screen"); 
     system("color 1F"); 

     // Program - Setup 
     int input; 
     int x; 
     int y; 
     char ny; //Dont declare it as array ny[10] 

     // Program - Start 
     cout << "Please choose an operation from the following." << endl << endl; 
     cout << "1. Addition \n2. Subtraction \n3. Multiplication \n4. Division" <<endl << endl; 
     cin >> input; 
     if (input == 1) goto addition; 
     if (input == 2) goto subtraction; 
     if (input == 3) goto multiplication; 
     if (input == 4) goto division; 
     cin.get(); 

    addition: 

     // Addition - Properties 
     system("cls"); 
     system("title Basic Calculator - Addition"); 
     system("color 2F"); 

     // Addition - Start 
     cout << "Please input your first number." << endl; 
     cin >> x; 
     cout <<endl << "Please input your second number."<< endl << endl; 
     cin >> y; 
     cout <<endl <<endl << "The answer is " << x+y << ".\a" << endl << endl; 
     cout << "Do you want to continue? N/Y" << endl; 
     cin >> ny; 

     if (ny == 'Y'|| ny == 'y') goto start; //Check for both Y & y 
     if (ny == 'N' || ny == 'n') goto end; //Check for both N & n 

     cin.get(); 

    subtraction: 

    multiplication: 

    division: 

    end: 
     // End - Properties 
     system("cls"); 
     system("title Basic Calculator - End"); 
     system("color 4F"); 

     // End - Start 

     cout << "Are you sure you want to end? N/Y" << endl; 
     cin >> ny; 

     if (ny == 'N' || ny == 'n') goto start; 

     cin.get(); 

     return 0; 
    } 
1

Сделать все, что сказал jmstoker, за исключением 1) и 3).Вместо того, чтобы изменить код

if (ny[0] == 'Y') goto start; 
if (ny[0] == 'N') goto end; 

Он работает по крайней мере в моем компиляторе (Microsoft Visual C++ 2011 Express)

Вот полный код

#include <iostream> 

using namespace std; 

int main() 
{ 
start: 
    // Program - Properties 
    system("cls"); 
    system("title Basic Calculator - Main Screen"); 
    system("color 1F"); 

    // Program - Setup 
    int input; 
    int x; 
    int y; 
    char ny [10]; 

    // Program - Start 
    cout << "Please choose an operation from the following." << endl << endl; 
    cout << "1. Addition \n2. Subtraction \n3. Multiplication \n4. Division" <<endl << endl; 
    cin >> input; 
    if (input == 1) goto addition; 
    if (input == 2) goto subtraction; 
    if (input == 3) goto multiplication; 
    if (input == 4) goto division; 
    cin.get(); 

addition: 

    // Addition - Properties 
    system("cls"); 
    system("title Basic Calculator - Addition"); 
    system("color 2F"); 

    // Addition - Start 
    cout << "Please input your first number." << endl; 
    cin >> x; 
    cout <<endl << "Please input your second number."<< endl << endl; 
    cin >> y; 
    cout <<endl <<endl << "The answer is " << x+y << ".\a" << endl << endl; 
    cout << "Do you want to continue? N/Y" << endl; 
    cin >> ny; 

    if (ny[0] == 'Y') goto start; 
    if (ny[0] == 'N') goto end; 

    cin.get(); 

subtraction: 

multiplication: 

division: 

end: 
    // End - Properties 
    system("cls"); 
    system("title Basic Calculator - End"); 
    system("color 4F"); 

    // End - Start 
    cout << "Are you sure you want to end? N/Y" << endl; 
    cin >> ny; 

    if (ny[0] == 'N') goto start; 

    cin.get(); 

    return 0; 
} 
+0

Хороший улов на # 1 @BlueBlobb. Я исправил свое решение – jmstoker

Смежные вопросы