gpt4 book ai didi

c++ - 如何使输入接受字符串和整数? C++

转载 作者:太空宇宙 更新时间:2023-11-04 15:19:27 25 4
gpt4 key购买 nike

是否有可能,假设您尝试进行计算,因此主要变量类型可能是 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,但是否可以使用转换或其他方式...

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

最佳答案

一种方法是从 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;
}
}

关于c++ - 如何使输入接受字符串和整数? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22741138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com