程序应读取2个整数并根据键盘引入的符号计算总和或乘积。如果您在任何给定的设备上按q,则必须退出。
#include "stdafx.h"
#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
char k, l ='h',c;
int a,b,s, p;
aici: while (l != 'q')
{
cin >> a;
if (_kbhit() == 0) //getting out of the loop
{
c = a;
if (c == 'q')
{
l = 'q';
goto aici;
}
}
cin >> b;
if (_kbhit() == 0)
{
c = b;
if (c == 'q')
{
l = 'q';
goto aici;
}
}
k = _getch();
if (_kbhit() == 0)
{
c = k;
if (c == 'q')
{
l = 'q';
goto aici;
}
}
if (k == '+')
{
s =(int)(a + b);
cout << s;
}
if (k == '*')
{
p = (int)(a*b);
cout << p;
}
}
return 0;
}
它希望a和b都是整数,因此输入&#39; q&#39;弄得一团糟。 是否有可能使程序工作而不将a和b声明为chars?
答案 0 :(得分:0)
你不需要在cin中使用goto和kbhit()。 一个简单的方法是:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a,b;
string A, B
char k;
while(1)
{
cin >> A;
if(A == "q") break;
cin >> B;
if(B == "q") break;
a = atoi(A.c_str());
b = atoi(B.c_str());
cin >> k;
if(k == 'q') break;
if (k == '+')
cout << (a + b);
if (k == '*')
cout << (a*b);
}
}
答案 1 :(得分:0)
您无法获得想要走这条路的位置。标准输入流读取将阻止,阻止您查找&#39; q&#39;并退出。
而是查看&#39; q&#39;的所有输入。因为它有它并在你有完整的消息后将它转换为你需要的值。类似的东西:
while (int input = _getch()) != 'q') // if read character not q
{
accumulate input into tokens
if enough complete tokens
convert numeric tokens into number with std::stoi or similar
perform operation
print output
}
你可以按照
的方式做点什么std::stringstream accumulator;
while (int input = _getch()) != 'q') // if read character not q
{
accumulator << std::static_cast<char>(input);
if (got enough complete tokens)// this be the hard part
{
int a;
int b;
char op;
if (accumulator >> a >> b >> op)
{ // read correct data
perform operation op on a and b
print output
}
accumulator.clear(); // clear any error conditions
accumulator.str(std::string()); // empty the accumulator
}
}