你怎么能输入字符串和int? C ++

时间:2014-03-30 06:47:12

标签: c++

是否有可能,比如说你试图进行计算,所以主变量类型可能是int ...但作为程序的一部分,你决定做一个while循环并为现有目的抛出一个if语句。 你有一个cin>>那就是接受一个数字来运行计算,但是你还需要一个他们想要退出的输入:

以下是一些与

配合使用的代码
#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,但可以使用转换或其他东西......

另一件事是有更好的方法来打破循环或是最常见的方式吗?

3 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:2)

您可以从输入流中将输入读取为字符串。检查它是否“离开”#39;并退出..如果不是尝试将其转换为数字并调用func1 ..请查看atoi或boost :: lexical_cast&lt;&gt;

也是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;

    }
}

答案 2 :(得分: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

}