![](/img/trans.png)
[英]code::blocks, how to put the linker option `-lstdc++` at the end of the compiler command?
[英]How to put EOF(end of file ) in code::blocks?
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int grade,
aCount = 0,
bCount = 0,
cCount = 0,
dCount = 0,
fCount = 0;
cout << "Enter the letter grades." << endl
<< "Enter the EOF character to end input." << endl;
while ( ( grade = cin.get() ) != EOF ) {
switch ( grade ) {
case 'A':
case 'a':
++aCount;
break;
case 'B':
case 'b':
++bCount;
break;
case 'C':
case 'c':
++cCount;
break;
case 'D':
case 'd':
++dCount;
break;
case 'F':
case 'f':
++fCount;
break;
case '\n':
case '\t':
case ' ':
break;
default:
cout << "Incorrect letter grade entered."
<< " Enter a new grade." << endl;
break;
}
}
cout << "\n\nTotal for each letter grade are:"
<< "\nA: " << aCount
<< "\nB: " << bCount
<< "\nC: " << cCount
<< "\nD: " << dCount
<< "\nF: " << fCount << endl;
return 0;
}
我构建并运行它,它在第19行(即带有while标头的行)显示“尚未声明EOF”。 我一一键入确切的代码。
EOF
宏在cstdio
定义,但是使用C ++风格的IO通常比使用C风格的IO更好。 与其检查返回值是否为EOF
,不如检查cin.eofbit
(或者,由于其他问题,可能是cin.failbit
),所以cin.failbit
。 您可以通过尝试将其评估为bool
来检查流的failbit
,如下所示。
如果将for循环替换为while循环,则为
for (char grade = cin.get(); cin; grade = cin.get()) {
它应该更好地工作(在这种情况下,您也应该摆脱最初的grade
声明,因为它仅在循环中使用,并且应该在其中声明)。
编辑:
这可以进一步简化。 get
方法支持传递字符引用,因此您可以调用cin.get(grade)
而不是grade = cin.get()
。 这样做的好处是,在传递字符引用时, get
返回流的副本,因此您可以同时进行读取和检查状态。 使用此方法,您需要提前声明grade
,但是循环可以从以下开始
while (cin.get(grade)) {
while ( ( grade = cin.get() ) != EOF ) {
在上面的行中,您仅将成绩作为输入。 EOF也应该有一个cin.get()
,除非它不起作用。 执行此操作时,您需要首先将EOF声明为char,如上一行所示,比较是在两个字符之间进行的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.