I learned C two or so years ago, and I recently (last year) decided to teach myself cxx. I never got around to doing it until now. So I have this book called
C++ Primer 2nd Edition by Stanley B. Lippman. Exercise 0-3 tells me to write a program that will count the amount of blanks, tabs, newlines, and characters (without white spaces) of an input. Few pages earlier it gave a similar program:
/*
*This program reads a character at a time from standard input
*until end-of file is encountered. It keeps a count of both the number of
*characters and the number of lines it reads. Its output is of the following form:
* lineCount characterCount
#include <iostream.h>
int main ()
{
char ch;
int lineCnt=0, charCnt=0;
while(cin.get(ch))
{
switch(ch)
{
case '\t':
case ' ':
break;
case '\n':
++lineCnt;
break;
default:
++charCnt;
break;
}
}
cout<<lineCnt<<" "<<charCnt<<endl;
return 0;
}
So I based my program off of that (hey, if it's given, I'll take it):
#include <iostream.h>
int main ()
{
char ch;
int lineCnt=0, charCnt=0, tabCnt=0, blankCnt=0;
while(cin.get(ch))
switch(ch)
{
case '\t':
++tabCnt;
break;
case ' ':
++blankCnt;
break;
case '\n':
++lineCnt;
break;
default:
++charCnt;
break;
}
cout<<"\t\tTotal Characters: "<<charCnt<<"\n\n\nLines: "<<lineCnt<<"\nChars: "<<charCnt<<"\nTabs: "<<tabCnt<<"\nBlanks: "<<blankCnt<<endl;
return 0;
}
The output is as follows(I typed in "hello"):
EXECUTING:
/home/[username removed]/C++/Exercis0.3/Count
--------------------------------------------------------------
hello
And it just stays there... I asked my friend (been cxx programming for ~2.5 years now), and his initial thought was that it was in an infinite loop. I saw it as a possibility, but I didn't see why it would be stuck in an infinite loop, so I ran a test:
#include <iostream.h>
int main ()
{
char ch;
int lineCnt=0, charCnt=0, tabCnt=0, blankCnt=0;
while(cin.get(ch))
{
switch(ch)
{
case '\t':
++tabCnt;
cout<<"t";
break;
case ' ':
++blankCnt;
cout<<"b";
break;
case '\n':
++lineCnt;
cout<<"n";
break;
default:
++charCnt;
cout<<"d";
break;
}
cout<<" nothing\n";
}
cout<<"reached\n";
cout<<"\t\tTotal Characters: "<<charCnt<<"\n\n\nLines: "<<lineCnt<<"\nChars: "<<charCnt<<"\nTabs: "<<tabCnt<<"\nBlanks: "<<blankCnt<<endl;
return 0;
}
The output is as follows (I typed in "hello"):
EXECUTING:
/home/[username removed]/C++/Exercis0.3/Count
--------------------------------------------------------------
hello
d nothing
d nothing
d nothing
d nothing
d nothing
n nothing
As you can see it never leaves the while loop, but it's not an infinite loop. What is going on? Just tell me that, and I might be able to solve the problem on my own.