#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int grade;
char quit = 'a';
cout << "Input your grade (0-100): ";
cout << endl;
cin >> grade;
while (grade < 0) {
cout << "If you have a negetive grade....drop out! otherwise enter another grade" << endl;
cin >> grade;
}
while (quit != 'q') {
while (grade < 0) {
cout << "If you have a negetive grade....drop out! otherwise enter another grade" << endl;
cin >> grade;
}
if (grade == 100) {
cout << "You got a perfect grade!" << endl;
cout << "Letter grade: A" << endl;
}
else if (grade >= 90 && grade <= 100) {
cout << "Letter grade: A" << endl << endl;
}
else if (grade >= 80 && grade <= 89) {
cout << "Letter grade: B" << endl << endl;
}
else if (grade >= 70 && grade <= 79) {
cout << "Letter grade: C" << endl << endl;
}
else if (grade >= 60 && grade <= 69) {
cout << "Letter grade: D" << endl << endl;
}
else if (grade < 60) {
cout << "Letter grade: F" << endl << endl;
}
else {
cout << "Invalid grade!" << endl;
}
cout << " would you like to enter another grade? or press q to quit" << endl;
cin >> grade;
}
system("pause");
return 0;`enter code here`
}
答案 0 :(得分:2)
由于grade
var。您将grade
声明为int
。
如果您键入正确的int
,则效果很好,但如果您键入另一个char
ex :) q
或f
,则函数cin
无法识别{{1}或q
为f
类型。
如果int
输入,char
通过自己的流程。
您必须将cin
类型更改为grade
才能识别char
和char
两种输入。
如果您只想使用一个输入流,此实施代码将为您提供帮助。
int
答案 1 :(得分:1)
最小,可验证的例子:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int grade;
char quit = 'a';
cout << "Input your grade (0-100): ";
cout << endl;
cin >> grade;
while (quit != 'q') {
cout << " would you like to enter another grade? or press q to quit" << endl;
cin >> grade;
}
system("pause");
return 0;`enter code here`
}
使用quit
查看问题?
修改强>
我所做的是删除(大部分)与quit
或循环无关的行。
此时你应该注意到循环永远不会改变退出。
如果您遇到程序问题,找出错误的最佳方法之一是摆脱与错误无关的所有内容。随着时间的推移,你只能用你的思维来做这个。 Duuude!
当我在它的时候
处理用户输入的正确方法是将其作为字符串,然后将其转换为您想要的。
例如:
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
template <typename T>
T string_to( const std::string& s )
{
T value;
std::istringstream ss( s );
ss >> value >> std::ws;
if (!ss.eof()) throw std::invalid_argument("T string_to()");
return value;
}
int main()
{
std::cout << "Enter a number or 'q': ";
std::string s;
getline( std::cin, s );
if (s == 'q')
{
std::cout << "Good job! You entered 'q'.\n";
}
else
{
try
{
double x = string_to <double> ( s );
std::cout << "Good job! You entered '" << x << "'.\n";
}
catch (const std::exception& e)
{
std::cout << "Foo, you didn't obey instructions and made me " << e.what() << ".\n";
}
}
}