gpt4 book ai didi

c++ - 试图通过输入字母退出C++程序

转载 作者:行者123 更新时间:2023-12-03 07:15:42 24 4
gpt4 key购买 nike

我编写了一个程序,该程序为用户输入的数字生成一个乘法表:

#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
char userSelection;
int numForTable;
int col;
int row;

do
{
cout << "Please enter a number for your multiplication table: " << endl;
cin >> numForTable;

while (numForTable < 1 || numForTable > 10)
{
cout << "Please enter a number between 1 & 10." << endl;
cin >> numForTable;
}

cout << "\n"
<< "MULTIPLICATION TABLE: " << numForTable << "'s" << endl
<< "\n"
<< " " << 1;

for (col = 2; col <= numForTable; ++col)

cout << " " << col;
cout << endl;
cout << " ----|";


for (col = 2; col <= numForTable; ++col)

cout << "----|";
cout << endl;


for (col = 1; col <= numForTable; ++col)
{
cout << setw(2) << col << "|";

for (row = 1; row <= numForTable; ++row)

cout << setw(4) << col * row << "|";
cout << endl;
cout << " -|----";

for (row = 2; row <= numForTable - 1; ++row)

cout << "|----";
cout << "|----|";
cout << endl;
}
}
while (userSelection != 'q');

return 0;
}
它会不断要求用户输入一个数字,直到程序关闭为止,但我正在尝试这样做,以便在用户输入任何字母字母后再显示诸如“祝您有美好的一天”之类的消息时,程序会关闭

最佳答案

我完全用您的程序编写表,并且仅使机制在写表或退出程序之间切换。由于您的程序只为1-10之间的整数(即2-9)写表,因此我使用了char的ASCII码。这是代码。

#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
char userSelection;
int numForTable;
int col;
int row;

while(cin>>userSelection)
{
int numForTable = (int)userSelection - 48;

if(numForTable<2 or numForTable > 9) //because the limit of the table is between 1-10, that is 2-9
{
cout<<"Have a nice day"<<endl;
return 0;
}

else
{
cout << "\n"
<< "MULTIPLICATION TABLE: " << numForTable << "'s" << endl
<< "\n"
<< " " << 1;

for (col = 2; col <= numForTable; ++col)

cout << " " << col;
cout << endl;
cout << " ----|";


for (col = 2; col <= numForTable; ++col)

cout << "----|";
cout << endl;


for (col = 1; col <= numForTable; ++col)
{
cout << setw(2) << col << "|";

for (row = 1; row <= numForTable; ++row)

cout << setw(4) << col * row << "|";
cout << endl;
cout << " -|----";

for (row = 2; row <= numForTable - 1; ++row)

cout << "|----";
cout << "|----|";
cout << endl;
}
}
}

return 0;
}
首先,它将char输入更改为ASCII码,然后检查数字是否介于2到9之间,然后根据它执行程序。如果我有任何错误,请纠正我。

关于c++ - 试图通过输入字母退出C++程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64420684/

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