C++ 如何使输入采用字符串和int?c++;

C++ 如何使输入采用字符串和int?c++;,c++,C++,有没有可能,比如说你试图进行计算,使主要变量类型可能是int。。。但作为程序的一部分,您决定执行while循环,并出于现有目的抛出if语句。 您有一个cin>>,即输入一个数字来运行计算,但您还需要一个输入,以防他们想要退出: 这里有一些代码可以使用 #include <iostream> using namespace std; int func1(int x) { int sum = 0; sum = x * x * x; return sum; }

有没有可能,比如说你试图进行计算,使主要变量类型可能是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;
        }

    }
}
#包括
使用名称空间std;
int func1(int x)
{
整数和=0;
总和=x*x*x;
回报金额;
}
int main()
{
布尔重复=真;

cout您可以从输入流中以字符串形式读取输入。检查输入是否为“离开”和“退出”。如果不是,请尝试将其转换为数字并调用func1。查看atoi或boost::词法转换

另外,输入==“离开”
=
是相等运算符。
=
是赋值运算符

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;

    }
}
intmain(){

cout一种方法是从
cin
读取一个字符串。检查其值。如果它满足退出条件,则退出。如果不满足,则从字符串中提取整数并继续处理该整数

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;
    }
}
while(重复)
{
字符串输入;
cin>>输入;
如果(输入==“离开”| |输入==“离开”)
{
重复=错误;
}
其他的
{
int intInput=atoi(input.c_str());
你可以用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

}
int输入;
字符串s;
cint>>s;//从用户处读取字符串
溪流ss(s);;
ss>>input;//尝试转换为int
if(ss==0)//不是整数
{
如果(s==“leave”){//用户不想输入更多输入
//出口
}
其他的
{
//无效数据-某些字符串不是LEVE且不是整数
}
}
其他的
{

coutWhy not
while(true)
break
?如果传递字母数字字符串(如“abc”或“abc123”),atoi函数可能会返回无效的int数据