TheStache
TheStache

Reputation: 39

How can you make input take strings and int? c++

is it possible, say your trying to do calculations so the primary variable type may be int... but as a part of the program you decide to do a while loop and throw an if statement for existing purposes. you have one cin >> and that is to take in a number to run calculations, but you also need an input incase they want to exit:

Here's some code to work with

#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;
        }

    }
}

I'm aware they wont take leave cause input is set to int, but is it possible to use a conversion or something...

another thing is there a better way to break the loop or is that the most common way?

Upvotes: 3

Views: 4830

Answers (3)

rajenpandit
rajenpandit

Reputation: 1361

you can use like

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

}

Upvotes: 2

odedsh
odedsh

Reputation: 2624

You can read the input as a string from the input stream. Check if it is 'leave' and quit.. and If it is not try to convert it to a number and call func1.. look at atoi or boost::lexical_cast<>

also it is input == "leave" == is the equal operator. = is an assignment operator.

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;

    }
}

Upvotes: 2

R Sahu
R Sahu

Reputation: 206567

One way to do this is read a string from cin. Check its value. If it satisfies the exit condition, exit. If not, extract the integer from the string and proceed to procss the integer.

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;
    }
}

Upvotes: 3

Related Questions