gpt4 book ai didi

C++如何循环这个东西(初学者)

转载 作者:行者123 更新时间:2023-11-30 02:33:12 37 4
gpt4 key购买 nike

我正在弄清楚如何循环我的代码,现在它让我感到困惑,任何帮助将不胜感激,我是这里的初学者所以请不要骂我。

#include <iostream>
#include <string>
using namespace std;

int main()
{
string str;
char ans;

cout << "CONVERSION\n\n";
cout << "Base 11 to Decimal\n";
a:cout << "Base 11: ";
getline(std::cin, str);
const auto bad_loc = str.find_first_not_of("0123456789aA");
if (bad_loc != std::string::npos)
{
std::cerr << "Invalid Input\n";
goto a;
}
unsigned long ul = std::stoul(str, nullptr, 11);
cout << "Decimal: " << ul << "\n\n";
cout << "Do you want to continue (Y/N)? ";
cin >> ans;
if (ans == 'y')
{
goto a;
}
else if (ans == 'n')
{
cout <<"Name:\tXXXXXXXX\n";
cout <<"Course:\tXXXXXXXX";
cout <<"Section:\tXXXXXXXX\n";
cout <<"Schedule:\tXXXXXXXX\n";
cout <<"Professor:\tXXXXXXXX\n";
}
return 0;
}

输出应该是这样的

CONVERSION

Base 11 to Decimal
Base 11: B
Invalid Input!

Base 11: A
//blank
Do you want to continue (Y/N)? X
Invalid Answer! (Y/N)? Y
//blank
Base11:

我的问题是(1) 程序在“base11:”循环后停止,每当我回答 Y 和 (2) 如果我回答来自“你想要...”的任何字母,程序将结束。 (3) 如何解决这个问题。

最佳答案

我们初学者应该互相帮助不是吗?:)

程序看起来像下面这样

#include <iostream>
#include <string>
#include <limits>

int main()
{
std::cout << "CONVERSION\n\n";
std::cout << "Base 11 to Decimal\n";

char ans;

do
{
std::string s;

bool valid_input = false;
while ( !valid_input )
{
std::cout << "Base 11: ";

if ( !std::getline( std::cin, s ) ) break;

if ( !( valid_input = s.find_first_not_of( "0123456789aA" ) == std::string::npos ) )
{
std::cout << "Invalid Input\n\n";
}
}

if ( !valid_input )
{
std::cout << "See you later!" << std::endl;
break;
}

unsigned long value = std::stoul( s, nullptr, 11 );

std::cout << "Decimal: " << value << "\n\n";

std::cout << "Do you want to continue (Y/N)? ";
std::cin >> ans;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
} while ( ans == 'y' || ans == 'Y' );

std::cout <<"Name:\tXXXXXXXX\n";
std::cout <<"Course:\tXXXXXXXX";
std::cout <<"Section:\tXXXXXXXX\n";
std::cout <<"Schedule:\tXXXXXXXX\n";
std::cout <<"Professor:\tXXXXXXXX\n";

return 0;
}

如果输入看起来像

B
A
Y
C
AA
N

那么输出就是

CONVERSION

Base 11 to Decimal
Base 11: B
Invalid Input

Base 11: A
Decimal: 10

Do you want to continue (Y/N)? Y
Base 11: C
Invalid Input

Base 11: AA
Decimal: 120

Do you want to continue (Y/N)? N
Name: XXXXXXXX
Course: XXXXXXXXSection: XXXXXXXX
Schedule: XXXXXXXX
Professor: XXXXXXXX

注意语句

std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

跳过使用operator >>输入ans后输入的换行符。

关于C++如何循环这个东西(初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35745118/

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