虽然循环导致无限循环,但我不知道为什么 [英] While loop causing an infinite loop but I can't figure out why
问题描述
我正在从事一个C ++中的任务,旨在教我们更多关于对象和OOP。以下是我的代码。其要点是,用户输入一些输入,并且该程序计算元音(辅音)(由用户选择)的数量,输入的字符总数和行尾总数。
我有三个问题:
- 我注释掉的代码部分是导致无限循环。它导致
countChars
函数的输出无限打印,以及输出询问用户是否他们想放入更多 -
countChars
函数未正确计数EOL。我认为这很可能是因为我对EOL不熟悉。我如何在我的条件语句中表示它?如果我想说,增量如果它的值为'0',我说,if(variable == 0)
。 -
countChars
输出随机的计数负值。我注意到值的变化取决于我键入(除了EOL),但我不知道为什么我得到负值。我不知道如何解决它,除了使用unsigned int
并初始化值。
此外,我预见人们告诉我使用getline函数,但是我们有非常具体的说明使用 cin.get
(我们应该学习所有请求,请避免使用 getline
的修复。
头文件:
/ *
+ --------------------- ------------------- +
| CountChars |
+ ---------------------------------------- +
| -countVorC:Integer |
| -countEOL:Integer |
| -totalChars:Integer |
| -vowelCount:Boolean |
+ ---------------------------------------- +
| <<< constructor>> |
| CountChars()|
| + inputChars():|
| + vowelCheck(characterToCheck:Boolean)|
| + setVowelCount(VorC:character)|
| + getCountVorC():Integer |
| + getCountEOL():Integer |
| + getTotalChars():Integer |
| + getVowelCount():Boolean |
+ ---------------------------------------- +
* /
using namespace std;
#ifndef COUNTCHARS_H
#define COUNTCHARS_H
类CountChars
{
private:
unsigned int countVorC;
unsigned int countEOL;
unsigned int totalChars;
bool vowelCount;
public:
CountChars();
void inputChars();
bool vowelCheck(char characterToCheck);
void setVowelCount(char VorC);
int getCountVorC();
int getCountEOL();
int getTotalChars();
bool getVowelCount();
};
#endif
执行文件:
#include< iostream>
#include< iomanip>
#include< string>
#include< cctype>
#include< cstdio>
#includeCountChars.h
using namespace std;
CountChars :: CountChars()
{
unsigned int countVorC = 0;
unsigned int countEOL = 0;
unsigned int totalChars = 0;
bool vowelCount = false;
}
void CountChars :: inputChars()
{
int letter;
while((letter = cin.get())!= EOF&&& amp; letter!= EOF){
if(vowelCount == true&(vowelCheck )== true)){
countVorC ++;
}
else if(vowelCount == false&&(vowelCheck(letter)== false)){
countVorC ++;
}
if(isalpha(letter)){
totalChars ++;
}
if(letter =='\\\
'){
countEOL ++;
}
}
}
bool CountChars :: vowelCheck(char characterToCheck)
{
characterToCheck = toupper(characterToCheck);
if((isalpha(characterToCheck))&&
(characterToCheck =='A'|| characterToCheck =='E'||
characterToCheck =='I '|| characterToCheck =='O'||
characterToCheck =='U')){
return true;
}
else {
return false;
}
}
void CountChars :: setVowelCount(char VorC)
{
VorC = toupper(VorC);
if(VorC =='V'){
vowelCount = true;
}
else {
vowelCount = false;
}
}
int CountChars :: getCountVorC()
{
return countVorC;
}
int CountChars :: getCountEOL()
{
return countEOL;
}
int CountChars :: getTotalChars()
{
return totalChars;
}
bool CountChars :: getVowelCount()
{
return vowelCount;
}
主要:
#include< iostream>
#include< iomanip>
#include< string>
#include< cctype>
#include< cstdio>
#includeCountChars.h
using namespace std;
void printCounts(CountChars);
int main()
{
char VorC;
char repeat ='Y';
CountChars charCounter;
cout<< 欢迎来到字符计数器计划! << endl;
cout<< \ n你要计数元音还是辅音? << endl;
cout<< 键入'V'为元音,'C'为辅音:;
cin>> VorC;
cout<< endl;
while(toupper(VorC)!='V'&& toupper(VorC)!='C'){
cout< \\\
Sorry,这是一个无效的选择,请重试:;
cin>> VorC;
cout<< endl;
}
do {
cout< 您可以在下面输入输入。\\\
< endl;
charCounter.setVowelCount(VorC);
charCounter.inputChars();
cin.clear();
printCounts(charCounter);
cout<< \ n要输入新输入吗? << endl;
cout<< 键入'Y'表示yes或'N'表示no:;
cin>>重复;
cout<< endl;
while(toupper(repeat)!='Y'&& toupper(repeat)!='N'){
cout< \\\
Sorry,这是一个无效的选择,请重试:;
cin>>重复;
cout<< endl;
}
} while(toupper(repeat)=='Y');
cout<< \\\
Thank你使用字符计数器程序!\\\
< endl;
系统(pause);
return 0;
}
void printCounts(CountChars charCounter)
{
cout< \\\
Total characters:<< charCounter.getTotalChars()<< endl;
if(charCounter.getVowelCount()== true){
cout< 总元音:<< charCounter.getCountVorC()<< endl;
}
else {
cout<< 总辅音:< charCounter.getCountVorC()<< endl;
}
cout<< 总结束线:< charCounter.getCountEOL()<< endl;
}
cin.get()
返回 int
字母
while((letter = cin.get())!= EOF)
如果平滑 char
是无符号类型,因为它在某些机器上,那么这将永远不会计算为true,因为值 -1
(EOF的正常值)分配给(unsigned) char
,映射到0xFF,而当 0xFF (
与
int
-1 ),答案是false,所以循环继续。
这个修复是使用 int字母
而不是字母字母
。 (注意,如果 char
是一个有符号类型,那么代码有一个不同的问题,那么,代码为0xFF的字符通常为ÿ,y umlaut,U + 00FF,拉丁小写字母Y与DIAERESIS - 被误解为EOF。修复是相同的;使用 int信;
)。
EOF不是EOL
在同一个函数中,还有:
if ){
countEOL ++;
}
你知道信
不是EOF(因为循环检查)。此外,你想计数EOL,而不是EOF(每个文件只有一个EOF,虽然如果你继续尝试读取超过EOF,你会得到EOF反复返回)。您可能需要:
if(letter =='\\\
'){
countEOL ++;
}
或者你想定义EOL并比较:
const int EOL ='\\\
';
if(letter == EOL){
countEOL ++;
}
cin
在输入中留下换行符
在代码中:
cout<< 键入'V'为元音,'C'为辅音:;
cin>> char(VorC);
cout<< endl;
while(toupper(VorC)!='V'&& toupper(VorC)!='C'){
cout< \\\
Sorry,那是一个无效的选择,请重试:;
cin>> char(VorC);
cout<< endl;
}
第一个 cin
操作在输入流中离开换行符。如果使用类型为Y,那么下一个 cin
操作(循环内部)将读取换行符,并且既然换行符既不是'V'也不是C ',它会再次抱怨(但会等待更多的输入)。
添加 #include< limits>
并使用:
cin.ignore(numeric_limits< streamsize> :: max(),'\\\
');
读取换行符。
无法继续阅读 cin code> EOF之后
最后一部分,我想...
您注释掉的代码:
/ * do {
cout< 您可以在下面输入输入。\\\
< endl; * /
charCounter.setVowelCount(VorC);
charCounter.inputChars();
/ * cout<< 您要输入新输入吗?
cout<< 将Y代表是或N代替否:< endl;
cin>> char(repeat);
cout<< endl;
while(toupper(repeat)!='Y'&& toupper(repeat)!='N'){
cout< \\\
Sorry,这是一个无效的选择,请重试:;
cin>> char(repeat);
cout<< endl;
}
} while(toupper(repeat)=='Y'); * /
$ b b
请注意, charCounter.inputChars()
的调用不会停止,直到 cin
达到 EOF
。此时没有任何输入,因此循环中的 cin
(注释掉)将每次都会失败,从不生成'Y'。您需要清除 cin
上的错误,以便您可以输入更多数据,例如更多输入问题的答案。
我不知道你是否在阅读代码中混淆了EOL和EOF。也许你打算只读到一行的结尾而不是文件的结尾。然后你的循环条件(我提到的第一个)应该是:
int letter;
while((letter = cin.get())!= EOF&&&&&&!letter!='\\\
')//或者如果你定义EOL, / code>
你应该总是准备任何输入操作返回EOF,当你没有真正期望它,
乐观主义者!
构造函数不构造
我仍然有垃圾打印的问题,虽然。例如,它表示总字符数:-85899345。
我试图编译您的代码:
$ g ++ -O3 -g -std = c ++ 11 -Wall -Wextra -Werror -c CountChars.cpp
CountChars.cpp:在构造函数' CountChars :: CountChars()':
CountChars.cpp:13:18:error:unused variable'countVorC'[-Werror = unused-variable]
unsigned int countVorC = 0;
^
CountChars.cpp:14:18:error:unused variable'countEOL'[-Werror = unused-variable]
unsigned int countEOL = 0;
^
CountChars.cpp:15:18:error:unused variable'totalChars'[-Werror = unused-variable]
unsigned int totalChars = 0;
^
CountChars.cpp:16:10:error:unused variable'vowelCount'[-Werror = unused-variable]
bool vowelCount = false;
^
cc1plus:所有警告被视为错误
$
你已经在你的构造函数中声明了隐藏类成员的局部变量,所以你的构造函数实际上并不有用。垃圾数字是因为你从垃圾开始。
cin>>类似地,当我试图编译 Main.cpp $ c时,它不会在任何地方编译
Main.cpp $ c时,它不会在任何地方编译
$ b $ c>,我开始遇到错误:
$ g ++ -O3 -g -std = c ++ 11 -Wall -Wextra -Werror -c Main.cpp
Main.cpp:在函数'int main()'中:
Main.cpp:18:9:error:'operator>是'std :: istream {aka std :: basic_istream< char>}'和'char')
cin>> char(VorC);
^
Main.cpp:18:9:注意:候选项是:
在包含在/usr/gcc/v4.9.1/include/c++/4.9.1/iostream:40中的文件中:0,
从Main.cpp:1:
/usr/gcc/v4.9.1/include/c++/4.9.1/istream:120:7:note:std :: basic_istream< _CharT, _Traits> :: __ istream_type& std :: basic_istream< _CharT,_Traits> :: operator>>(std :: basic_istream< _CharT,_Traits> :: __ istream_type&(*)(std :: basic_istream< _CharT,_Traits> :: __ istream_type& _CharT = char; _Traits = std :: char_traits< char> ;; std :: basic_istream< _CharT,_Traits> :: __ istream_type = std :: basic_istream< char>]< near match>
operator>>(__ istream_type&(* __ pf)(__ istream_type&))
^
/usr/gcc/v4.9.1/include/c++/4.9.1/istream:120: 7:注意:参数1从'char'到'std :: basic_istream< char> :: __ istream_type& (*)(std :: basic_istream< char> :: __ istream_type&){aka std :: basic_istream< char> (*)(std :: basic_istream< char>&)}'
/usr/gcc/v4.9.1/include/c++/4.9.1/istream:124:7:note:std :: basic_istream< _CharT,_Traits> :: __ istream_type& std :: basic_istream< _CharT,_Traits> :: operator>>(std :: basic_istream< _CharT,_Traits> :: __ ios_type&(*)(std :: basic_istream< _CharT,_Traits> :: __ ios_type& _CharT = char; _Traits = std :: char_traits< char> ;; std :: basic_istream< _CharT,_Traits> :: __ istream_type = std :: basic_istream< char> ;; std :: basic_istream< _CharT,_Traits> :: __ ios_type = std :: basic_ios< char>]< near match>
operator>>(__ ios_type&(* __ pf)(__ ios_type&))
^
...
$
这里的问题是:
cin> char(VorC);
你真的不想要的演员:
$ b b
cin>> VorC;
您应该检查输入是否有效:
if(!(cin>> VorC))... process EOF或error ...
这个问题影响到 cin>>当然,
我不知道为什么它为你编译;它不应该这样做。有了固定的,它的作品。我遇到了'换行仍然输入',所以 inputChars()
函数在EOL之前有零个字符,等等现在由你来处理。 p>
I am working on an assignment in C++ meant to teach us more about objects and OOP. Below is my code. The gist of it is, the user enters some input, and the program counts the number of vowels or consonants (chosen by the user), the total number of characters entered, and the total number of end-of-lines.
I am having three issues:
- The portion of code I've commented out is causing an infinite loop when left in. It causes the output from the
countChars
function to be printed infinitely, as well as the output asking the user if they would like to put in more input. - The
countChars
function isn't counting EOL properly. I think it is most likely due to my unfamiliarity with the EOL. How do I signify it in my conditional statement? If I want to say, "increment if it has a value of '0'", I say,if (variable == 0)
. How do I tell C++ to increment if something is an EOL? countChars
outputs random, negative values for the counts. I do notice the values changing depending on what I type (except EOL), but I am not sure why I am getting negative values. I'm not sure how to fix it beyond using anunsigned int
and initializing the values.
Also, I foresee people telling me to use the getline function, but we had very specific instructions to use cin.get
(we're supposed to learn a bit of everything, after all) so please, avoid a fix that uses getline
.
Header file:
/*
+----------------------------------------+
| CountChars |
+----------------------------------------+
| -countVorC : Integer |
| -countEOL : Integer |
| -totalChars : Integer |
| -vowelCount : Boolean |
+----------------------------------------+
| <<constructor>> |
| CountChars() |
| +inputChars() : |
| +vowelCheck(characterToCheck : Boolean)|
| +setVowelCount(VorC : Character) |
| +getCountVorC() : Integer |
| +getCountEOL() : Integer |
| +getTotalChars() : Integer |
| +getVowelCount() : Boolean |
+----------------------------------------+
*/
using namespace std;
#ifndef COUNTCHARS_H
#define COUNTCHARS_H
class CountChars
{
private:
unsigned int countVorC;
unsigned int countEOL;
unsigned int totalChars;
bool vowelCount;
public:
CountChars();
void inputChars();
bool vowelCheck(char characterToCheck);
void setVowelCount(char VorC);
int getCountVorC();
int getCountEOL();
int getTotalChars();
bool getVowelCount();
};
#endif
Implementation file:
#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
#include <cstdio>
#include "CountChars.h"
using namespace std;
CountChars::CountChars()
{
unsigned int countVorC = 0;
unsigned int countEOL = 0;
unsigned int totalChars = 0;
bool vowelCount = false;
}
void CountChars::inputChars()
{
int letter;
while ((letter = cin.get()) != EOF && letter != EOF){
if (vowelCount == true && (vowelCheck(letter) == true)) {
countVorC++;
}
else if (vowelCount == false && (vowelCheck(letter) == false)) {
countVorC++;
}
if (isalpha(letter)) {
totalChars++;
}
if (letter == '\n') {
countEOL++;
}
}
}
bool CountChars::vowelCheck(char characterToCheck)
{
characterToCheck = toupper(characterToCheck);
if ((isalpha(characterToCheck)) &&
(characterToCheck == 'A' || characterToCheck == 'E' ||
characterToCheck == 'I' || characterToCheck == 'O' ||
characterToCheck == 'U')) {
return true;
}
else {
return false;
}
}
void CountChars::setVowelCount(char VorC)
{
VorC = toupper(VorC);
if (VorC == 'V') {
vowelCount = true;
}
else {
vowelCount = false;
}
}
int CountChars::getCountVorC()
{
return countVorC;
}
int CountChars::getCountEOL()
{
return countEOL;
}
int CountChars::getTotalChars()
{
return totalChars;
}
bool CountChars::getVowelCount()
{
return vowelCount;
}
Main:
#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
#include <cstdio>
#include "CountChars.h"
using namespace std;
void printCounts(CountChars);
int main()
{
char VorC;
char repeat = 'Y';
CountChars charCounter;
cout << "Welcome to the Character Counter Program!" << endl;
cout << "\nWould you want to count vowels or consonants?" << endl;
cout << "Type 'V' for vowels and 'C' for consonants: ";
cin >> VorC;
cout << endl;
while (toupper(VorC) != 'V' && toupper(VorC) != 'C') {
cout << "\nSorry, that was an invalid choice. Please try again: ";
cin >> VorC;
cout << endl;
}
do {
cout << "You may being typing input below.\n" << endl;
charCounter.setVowelCount(VorC);
charCounter.inputChars();
cin.clear();
printCounts(charCounter);
cout << "\nWould you like to enter new input?" << endl;
cout << "Type 'Y' for yes or 'N' for no: ";
cin >> repeat;
cout << endl;
while (toupper(repeat) != 'Y' && toupper(repeat) != 'N') {
cout << "\nSorry, that was an invalid choice. Please try again: ";
cin >> repeat;
cout << endl;
}
} while (toupper(repeat) == 'Y');
cout << "\nThank you for using the Character Counter Program!\n" << endl;
system("pause");
return 0;
}
void printCounts(CountChars charCounter)
{
cout << "\nTotal characters: " << charCounter.getTotalChars() << endl;
if (charCounter.getVowelCount() == true) {
cout << "Total vowels: " << charCounter.getCountVorC() << endl;
}
else {
cout << "Total consonants: " << charCounter.getCountVorC() << endl;
}
cout << "Total end-of-lines: " << charCounter.getCountEOL() << endl;
}
cin.get()
returns an int
You have:
char letter;
while ((letter = cin.get()) != EOF)
If the plain char
is an unsigned type, as it is on some machines, then this will never evaluate to true because the value -1
(the normal value for EOF) is assigned to an (unsigned) char
, it is mapped to 0xFF, and when 0xFF
is compared with an int
like EOF
(that is still -1
), the answer is false, so the loop continues.
The fix for this is to use int letter
instead of char letter
. (Note that there's a different problem with the code as written if char
is a signed type; then, the character with code 0xFF — often ÿ, y umlaut, U+00FF, LATIN SMALL LETTER Y WITH DIAERESIS — is misinterpreted as EOF. The fix is the same; use int letter;
).
I suspect, though, that this is only part of the trouble.
EOF is not EOL
In the same function, you also have:
if (letter == EOF) {
countEOL++;
}
You know that letter
is not EOF (because the loop checked that). Also, you wanted to count EOL, not EOF (there is only one EOF per file, though if you keep attempting read beyond EOF, you will get EOF returned repeatedly). You probably need:
if (letter == '\n') {
countEOL++;
}
or maybe you want to define EOL and compare to that:
const int EOL = '\n';
if (letter == EOL) {
countEOL++;
}
cin
leaves the newline in the input
In the code:
cout << "Type 'V' for vowels and 'C' for consonants: ";
cin >> char(VorC);
cout << endl;
while (toupper(VorC) != 'V' && toupper(VorC) != 'C') {
cout << "\nSorry, that was an invalid choice. Please try again: ";
cin >> char(VorC);
cout << endl;
}
The first cin
operation leaves the newline in the input stream. If the use typed 'Y', say, then the next cin
operation (inside the loop) will read the newline, and since the newline is neither 'V' nor 'C', it will complain again (but would then wait for more input).
Add #include <limits>
and use:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
to read past the newline.
Again, this isn't the whole problem.
Can't continue reading cin
after EOF
And the final installment, I think…
Your commented out code is:
/*do {
cout << "You may being typing input below.\n" << endl;*/
charCounter.setVowelCount(VorC);
charCounter.inputChars();
/*cout << "Would you like to enter new input?";
cout << "Type 'Y' for yes or 'N' for no: " << endl;
cin >> char(repeat);
cout << endl;
while (toupper(repeat) != 'Y' && toupper(repeat) != 'N') {
cout << "\nSorry, that was an invalid choice. Please try again: ";
cin >> char(repeat);
cout << endl;
}
} while (toupper(repeat) == 'Y');*/
Note that the call to charCounter.inputChars()
doesn't stop until cin
has reach EOF
. There isn't any more input at that point, so the cin
in the loop (that is commented out) will fail every time, never generating a 'Y'. You need to clear the errors on cin
so that you can enter more data, such as the answer to the 'more input' question.
I wonder if you've confused EOL and EOF in the reading code. Maybe you intended to read only to the end of a line rather than to the end of the file. Then your loop condition (the one I mentioned first) should be:
int letter;
while ((letter = cin.get()) != EOF && letter != '\n') // Or EOL if you define EOL as before
You should always be prepared for any of the input operations to return EOF when you didn't really expect it, as here.
Ever the optimist! The previous installment was not the final one.
The constructor doesn't construct
I still have the issue of junk being printed, though. For example, it says Total characters: -85899345.
I tried to compile your code:
$ g++ -O3 -g -std=c++11 -Wall -Wextra -Werror -c CountChars.cpp
CountChars.cpp: In constructor ‘CountChars::CountChars()’:
CountChars.cpp:13:18: error: unused variable ‘countVorC’ [-Werror=unused-variable]
unsigned int countVorC = 0;
^
CountChars.cpp:14:18: error: unused variable ‘countEOL’ [-Werror=unused-variable]
unsigned int countEOL = 0;
^
CountChars.cpp:15:18: error: unused variable ‘totalChars’ [-Werror=unused-variable]
unsigned int totalChars = 0;
^
CountChars.cpp:16:10: error: unused variable ‘vowelCount’ [-Werror=unused-variable]
bool vowelCount = false;
^
cc1plus: all warnings being treated as errors
$
You've declared local variables in your constructor that hide the class members, so your constructor doesn't actually usefully construct. The junk numbers are because you start with junk.
cin >> char(VorC)
does not compile everywhere
Similarly, when I tried to compile Main.cpp
, I got errors starting:
$ g++ -O3 -g -std=c++11 -Wall -Wextra -Werror -c Main.cpp
Main.cpp: In function ‘int main()’:
Main.cpp:18:9: error: ambiguous overload for ‘operator>>’ (operand types are ‘std::istream {aka std::basic_istream<char>}’ and ‘char’)
cin >> char(VorC);
^
Main.cpp:18:9: note: candidates are:
In file included from /usr/gcc/v4.9.1/include/c++/4.9.1/iostream:40:0,
from Main.cpp:1:
/usr/gcc/v4.9.1/include/c++/4.9.1/istream:120:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__istream_type& (*)(std::basic_istream<_CharT, _Traits>::__istream_type&)) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>] <near match>
operator>>(__istream_type& (*__pf)(__istream_type&))
^
/usr/gcc/v4.9.1/include/c++/4.9.1/istream:120:7: note: no known conversion for argument 1 from ‘char’ to ‘std::basic_istream<char>::__istream_type& (*)(std::basic_istream<char>::__istream_type&) {aka std::basic_istream<char>& (*)(std::basic_istream<char>&)}’
/usr/gcc/v4.9.1/include/c++/4.9.1/istream:124:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__ios_type& (*)(std::basic_istream<_CharT, _Traits>::__ios_type&)) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>; std::basic_istream<_CharT, _Traits>::__ios_type = std::basic_ios<char>] <near match>
operator>>(__ios_type& (*__pf)(__ios_type&))
^
…
$
The problem here is the:
cin >> char(VorC);
You really don't want the cast there:
cin >> VorC;
You arguably should check that the input works:
if (!(cin >> VorC)) …process EOF or error…
This same problem afflicts the cin >> char(repeat);
, of course.
I don't know why it compiled for you; it should not have done so. With that fixed, it sort of works. I ran into the 'newline still in input' so the inputChars()
function got zero characters before EOL, etc. Now it is up to you to deal with that.
这篇关于虽然循环导致无限循环,但我不知道为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!