This is the function of a larger program. This function just figures out how many characters are in an alphanumeric word. Weird thing is, it counts apostrophes when running it in Xcode, but not after compiling and running it in Terminal. Any suggestions?
#include <iostream>
#include <iomanip>
#include <ctype.h>
using namespace std;
int WordLength();
void DisplayTable(int WF[]);
int main()
{
int WordFrequency[16]={0};
int TempLengthStorage=0;
TempLengthStorage=WordLength();
while (TempLengthStorage!=0)
{
if (TempLengthStorage==1)//skipping subscript 0 - not using it
++WordFrequency[1];
else if (TempLengthStorage==2)
++WordFrequency[2];
else if (TempLengthStorage==3)
++WordFrequency[3];
else if (TempLengthStorage==4)
++WordFrequency[4];
else if (TempLengthStorage==5)
++WordFrequency[5];
else if (TempLengthStorage==6)
++WordFrequency[6];
else if (TempLengthStorage==7)
++WordFrequency[7];
else if (TempLengthStorage==8)
++WordFrequency[8];
else if (TempLengthStorage==9)
++WordFrequency[9];
else if (TempLengthStorage==10)
++WordFrequency[10];
else if (TempLengthStorage==11)
++WordFrequency[11];
else if (TempLengthStorage==12)
++WordFrequency[12];
else if (TempLengthStorage==13)
++WordFrequency[13];
else if (TempLengthStorage==14)
++WordFrequency[14];
else if (TempLengthStorage>=15)
++WordFrequency[15];
TempLengthStorage=WordLength();
}
DisplayTable(WordFrequency);
}
int WordLength()
{
int LetterCount=0;
int EndOfWord=0;
char Input;
char NextChar;
cin.get(Input);
while (EndOfWord!=1 && !cin.eof())
{
if (Input==' ' || Input=='\n' || Input=='.' || Input=='!' || Input=='?' || Input==',')
{//do nothing if whitespace or punctuation, essentially skips over them
}
else if (Input=='-')
{
NextChar=cin.peek();
if ((isalpha(NextChar)) || (isnumber(NextChar)))//this includes the hyphen in words that have hyphens (refer to funtion notes)
++LetterCount;
if (NextChar=='\n')//for cases where the hyphen doesn't add to word length (refer to function notes)
{
cin.get(Input);//dont count it and get next character
}
}
else if (Input=='\'')
++LetterCount;
else if ((isalpha(Input)) || (isnumber(Input)))
{
++LetterCount;
NextChar=cin.peek();
if (NextChar==' ' || NextChar=='\n' || NextChar=='.' || NextChar=='!' || NextChar=='?' || NextChar==',' || NextChar==')')//included ) as a condition to end words for cases such as (219)
{
EndOfWord=1;
}
}
cin.get(Input);
}
return LetterCount;
}
void DisplayTable(int WF[])
{
int TotalWords=0;
float TotalLetters=0;//made a float for float based masth later on when finding average
float Average=0;
cout << endl;
cout << "Word Length Frequency" << endl;
cout << "----------- ---------" << endl;
for (int i=1; i<=15; ++i)
{
/*This portion of the loop displays the table*/
cout << " ";
cout << setw(2) << i;
cout << " ";
cout << WF[i] << endl;
/*this portion of the loop does the calculations needed to find the average word length*/
TotalWords += WF[i];
TotalLetters += (i * WF[i]);
}
cout << "\nTotal Words = " << TotalWords << endl << endl;
cout << "Total Letters = " << TotalLetters << endl << endl;
Average = TotalLetters/TotalWords;
cout << "Average Word Length: " << Average << endl;
}
I used "Ain't" in both situations, just for testing purposes.
Related
Here's my current code:
#include <iostream>
#include <set>
using namespace std;
int main()
{
string numOne, numTwo, numThree;
int pointOne, pointTwo, pointThree, totalPoint;
set<string> ansOne = { "TOE", "TONGUE", "TOOTH" };
cout << "Give A Body Part That Starts With The Letter T";
cout << "\n1. ";
cin >> numOne;
if (ansOne.find(numOne) == ansOne.end())
{
ansOne.erase(numOne);
cout << "Wrong!";
pointOne = 0 + 0;
}
else
{
cout << "Nice, You got a Point!";
pointOne = 1 + 0;
}
cout << "\n2. ";
cin >> numTwo;
if (ansOne.find(numTwo) == ansOne.end())
{
ansOne.erase(numTwo);
cout << "Wrong!";
pointTwo = 0 + pointOne;
}
else
{
cout << "Nice, You got a Point!";
pointTwo = 1 + pointOne;
}
cout << "\n3. ";
cin >> numThree;
if (ansOne.find(numThree) == ansOne.end())
{
ansOne.erase(numThree);
cout << "Wrong!";
pointThree = 0 + pointTwo;
}
else
{
cout << "Nice, You got a Point!";
pointThree = 1 + pointTwo;
}
totalPoint = pointOne + pointTwo + pointThree;
cout << "\n" << totalPoint;
}
What I want to do is, if the answer is after they put the answers, and if the word is in there, I want to erase that word from the set so they can't duplicate the answer. But it's not getting erased from the set.
Per your declared logic, you put the erase in the wrong branch of the if, only erasing a word when the word wasn't in the set already, and not erasing it when it was. The first if/else block would be fixed with:
if (ansOne.find(numOne) == ansOne.end())
{
// Removed ansOne.erase(numOne); here, because you just confirmed it's not in ansOne
cout << "Wrong!";
pointOne = 0;
}
else
{
ansOne.erase(numOne); // It's in ansOne, remove it so it can't be guessed again
cout << "Nice, You got a Point!";
pointOne = 1;
}
Similar changes would be made to the other two if/else blocks.
Note that this code would be much simpler with a for loop that runs three times and maintains the running total, rather than individual variables for each of three nearly identical tests. For example, the fixed version of your code could simplify to:
int main()
{
string userinput; // Just one string for input
int totalPoints = 0; // Just one score counter
set<string> ansOne = { "TOE", "TONGUE", "TOOTH" };
cout << "Give A Body Part That Starts With The Letter T";
for (int i = 1; i <= 3; ++i) {
cout << '\n' << i << ". "; // Number prompts dynamically
cin >> userinput;
const auto inputloc = ansOne.find(userinput); // Storing off iterator speeds erasure later (admittedly not meaningful for three element set
if (inputloc == ansOne.end())
{
cout << "Wrong!";
}
else
{
ansOne.erase(inputloc); // Erase with iterator to element found
cout << "Nice, You got a Point!";
++totalPoints;
}
}
cout << '\n' << totalPoint << '\n';
}
For example, if I wanted to find the number of times that the word "MY" appears in a user-inputted sentence, how would I do that? Is it even possible to do this if I'm reading in the sentence one character at a time with a while-loop?
Sample input would be something like: "My house is here"
My current output is:
Number of words.........4
Number of uppercase letters.........1
Number of lowercase letters........12
Number of vowels.........6
Number of substring MY.........0
where number of substring MY should be 1.
Here's what I currently have:
#include <iostream>
#include <string>
#include <cstring>
#include <iomanip>
using namespace std;
bool isvowel(char c) {
if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' || c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
return true;
} else {
return false;
}
}
int main() {
char c;
int words = 0;
int upperCount = 0;
int lowerCount = 0;
int vowels = 0;
int my = 0;
cout << "Enter a sentence: ";
while (cin.get(c), c != '\n') {
if (isupper(c)) {
upperCount++;
}
if (islower(c)) {
lowerCount++;
}
if (isspace(c)) {
words++;
}
if (isvowel(c) == true) {
vowels++;
}
if (c == 'M' || c == 'm') {
if (c+1 == 'Y' || c+1 == 'y') {
my++;
}
}
}
cout << left << "Number of words" << setfill('.') << setw(10) << right << words + 1 << endl;
cout << left << "Number of uppercase letters" << setfill('.') << setw(10) << right << upperCount << endl;
cout << left << "Number of lowercase letters" << setfill('.') << setw(10) << right << lowerCount << endl;
cout << left << "Number of vowels" << setfill('.') << setw(10) << right << vowels << endl;
cout << left << "Number of substring MY" << setfill('.') << setw(10) << right << my << endl;
system("Pause");
return 0;
}
This can be done in many ways, you almost have one. I will not give you the exact solution but you can try something like this: (written in Java)
// String sentence = "My house is here";
// word = "My"
private int getWordCount(String sentence, String word) {
char[] charArr = sentence.toCharArray();
String currWord = "";
int count = 0;
for(char c : charArr) {
if(c != ' ') { currWord += c; } // if c is not space it gets appended to the current word
else {
if(currWord.toLowerCase().equals(word.toLowerCase())) {
count++;
}
currWord = "";
}
}
return count;
}
Keep a track of the current string. If the current character is not a whitespace, append it to the string; else, the string becomes empty.
For each string, you could compare it to the target string. This comparison will have O(n) complexity, where n is the length of the string.
To optimise it further, you could build a trie for the target string. Since you're already processing one character at a time, the string matching could be done in O(1) instead of O(n).
The game does not want to exit/close. Somebody enlighten me as to what I've missed? Also, do you think i have coded the game properly?
Source code:
#include<iostream>
#include<iomanip>
using namespace std;
void drawBoard(char board[][3]);
char checkWinner3by3(char board[][3]);
int main()
{
char board[3][3] = {{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};
int row;
int column;
bool is_move;
bool is_row;
bool is_column;
cout<<"********** TIC TAC TOE ************\n";
{
is_move = false;
is_row = false;
is_column = false;
drawBoard(board);
cout << "Player ";
if(player == 'X')
{
cout << 1;
}
else
{
cout << 2;
}
cout << "'s turn:" << endl;
is_move = false;
while(!is_move)
{
while(!is_row)
{
cout << "Row: ";
cin >> row;
if(row == 1 || row == 2 || row == 3)
{
is_row = true;
}
else
{
cout << endl << "Invalid row!" << endl;
}
}
/
is_column = false;
while(!is_column)
{
cout << "Column: ";
cin >> column;
if(column == 1 || column == 2 || column == 3)
{
is_column = true;
}
else
{
cout << endl << "Invalid column!" << endl;
}
}
Irrelevant stuff here.
if(board[row-1][column-1] == ' ')
{
board[row-1][column-1] = player;
is_move = true;
if(player == 'X')
{
player = 'O';
}
else
{
player = 'X';
}
}
else
{
cout<<"The selected space is occupied!" << endl;
cout << "Select a different space:" << endl << endl;
drawBoard(board);
}
}
cout << endl;
Checking the winner
winner = checkWinner3by3(board);
if(winner == 'X' || winner == 'O')
{
drawBoard(board);
cout<<"Congratulations! Player ";
if(winner == 'X')
{
cout << 1;
}
else
{
cout << 2;
}
cout<<" is the winner!"<<endl;
}
else if(winner == 'T')
{
drawBoard(board);
cout << "It's a tie!" << endl;
}
}
system("pause");
return 0;
}
Board is here.
void drawBoard(char board[][3])
{
char print[][3] = {{' ',' ',' '},
{' ',' ',' '},
{' ',' ',' '}};
cout << " 1 2 3" << endl;
cout << " +---+---+---+" << endl;
cout << " 1" << " | " << print[0][0] << " | " << print[0][1] << " | "
<< print[0][2] << " | " << endl;
cout << " +---+---+---+" << endl;
cout << " 2" << " | " << print[1][0] << " | " << print[1][1] << " | "
<< print[1][2] << " | " << endl;
cout << " +---+---+---+" << endl;
cout << " 3" << " | " << print[2][0] << " | " << print[2][1] << " | "
<< print[2][2] << " | " << endl;
cout << " +---+---+---+" << endl;
}
char checkWinner3by3(char board[][3])
{
for(i=0; i<3; i++)
{
if(board[i][0]==board[i][1] && board[i][0]==board[i][2])
{
return board[i][0];
}
}
for(i=0; i<3; i++)
{
if(board[0][i]==board[1][i] && board[0][i]==board[2][i])
{
return board[0][i];
}
}
if(board[0][0]==board[1][1] && board[1][1]==board[2][2])
{
return board[0][0];
}
if(board[0][2]==board[1][1] && board[1][1]==board[2][0])
{
return board[0][2];
}
return ' ';
}
This is the entire source code - i wanted to make a game and i honestly think this is the best way to start by knowing what i can do to improve it.
You have not declared the variable "player" & "winner" yet have initialized them...but this could be because the full code is not displayed.
you have system("pause") before return... why did you put that there?
...now that I look further its all screwed up
I made a Tic-Tac-Toe once and it's kinda similar to what your trying to do apart from selection via 2d array, you should consider using parts of it to correct your code.
#include <iostream>
#include <iomanip>
using namespace std;
char* cBox{ new char[9]{ '1', '2', '3', '4', '5', '6', '7', '8', '9' } }; // cBox are tic tac toe squares
char* PcBox{ nullptr }; // PcBox will be pointers to cBox squares
bool EndGame{ true }, VailidMove{ true }, WinGame{ true }; // Global bool varibles are initially set to true to test for validity
size_t PlayerMove{ 1 };
int Move;
int score(size_t PlayerMove); /********************************/
void Board(); /* */
void error(); /* Function Prototypes */
void GameOver(); /* */
int scoreboard(int score1, int score2); /********************************/
int main() {
int score1{}, score2{};
int sum{};
int winner{};
int const total{ 756 };
char PlayerIcon;
// do while loop
do {
// print scoreboard
scoreboard(score1, score2);
// Print board
Board();
// This conditional forces the first Player to be 'X'... Player2 'O'
(PlayerMove == 1) ? PlayerIcon = 'X' : PlayerIcon = 'O';
// Time for the player to move
cout << endl << setw(51) << "Player" << PlayerMove << "'s move:";
cin >> Move;
VailidMove = false; // ValidMove is assigned to false within the "do loop"...it will remain false until a valid key is entered..
//... it's conditionally tested within the while loop until the player's move is true(valid)
// Loop until we get a valid move
while (!VailidMove) {
system("CLS"); // Clear the screen
(PcBox = &cBox[Move - 1]); // For our move selection, point PcBox to the address of the array cBox[index] on the free store
if (!(*PcBox == 'X' || *PcBox == 'O') && (cin) && Move != 0) // this checks the location for PlayerIcons...as one cannot place a new playericon where one already resides...
// ...also tests whether a legit key input..aka not a "letter" or a "0"
{
VailidMove = true;
*PcBox = PlayerIcon; // A valid playericon is placed in a free box on the board
}
else
{
error(); // Anything else other than a valid selection will throw an error and return to the beginning of the block...
return main(); // ...querying the player for a valid selection until one is entered
}
};
EndGame = false; // Again like "VailidMove" we set EndGame to false to test against the following conditions
// This is a combintion of seperate win conditions... 3 the same, across or diagonal over entire board
if (cBox[0] == cBox[1] && cBox[1] == cBox[2])
GameOver();
if (cBox[0] == cBox[4] && cBox[8] == cBox[4])
GameOver();
if (cBox[1] == cBox[4] && cBox[7] == cBox[4])
GameOver();
if (cBox[2] == cBox[4] && cBox[6] == cBox[4])
GameOver();
if (cBox[2] == cBox[8] && cBox[5] == cBox[8])
GameOver();
if (cBox[3] == cBox[0] && cBox[6] == cBox[0])
GameOver();
if (cBox[3] == cBox[4] && cBox[5] == cBox[4])
GameOver();
if (cBox[6] == cBox[8] && cBox[7] == cBox[8])
GameOver();
// If the board is full and no one wins then it is a tie...this piece just sums up all the player icons as ascii integers...
// ...if the board is full of them, then the sum is 756 and it is a tie.
sum += (*PcBox); // add player icon to sum...Ascii to int
if ((sum == total) && !EndGame) // if sum of playericon for entire board = 756...no win
{
EndGame = true;
WinGame = false;
sum = 0; //reset sum to zero
scoreboard(score1, score2);
}
// End/Win game conditions
if (EndGame) { // game over? test choices
if (WinGame) { // We nest this here soley if EndGame & WinGame is true... else if just WinGame is true its a draw
if (PlayerMove == 1) { score1 = score(PlayerMove); }
if (PlayerMove == 2) { score2 = score(PlayerMove); }
scoreboard(score1, score2);
winner = PlayerMove;
}
Board();
if (WinGame)
cout << "\n" << setw(51) << "PLAYER " << winner << " WINS!" << endl;
cout << endl << setw(57) << "Game Over!!!" << endl;
cout << endl << setw(59) << "Play again y/n?"; // Query the player for another game
char PlayAgain;
cin >> PlayAgain;
// This resets the board, if the player wants another game, it uses a for loop to increment simultaneously it's "ascii integer", along side it's "int" equivalent...
//... overwriting & reseting the board from 1-9 with the original characters
if (PlayAgain == 'y' || PlayAgain == 'Y') {
EndGame = false;
for (int i = 0, j = 49; i < 9 && j <= 57; i++, j++) // ASCII int 49 = char '1'... to 57 = char '9'
{
(cBox[i] = (char)j); // Clear the board
}
sum = 0; // Reset sum to zero
system("CLS"); // Clear the screen
}
PlayerMove = 1;
if (PlayAgain == 'n') {
EndGame = true;
}
}
else
{
(PlayerMove == 1) ? PlayerMove = 2 : PlayerMove = 1;
}
} while (!EndGame);
delete[] cBox; // Free up memory...
cBox = nullptr;
cout << "\n\t\t\t\t\t";
return 0;
}
// Function definiton to print game board
inline void Board() {
{
cout << endl << '\n' << '\n' << endl;
cout << setw(50) << cBox[0] << "|" << cBox[1] << "|" << cBox[2] << endl;
cout << setw(54) << "-+-+-" << endl;
cout << setw(50) << cBox[3] << "|" << cBox[4] << "|" << cBox[5] << endl;
cout << setw(54) << "-+-+-" << endl;
cout << setw(50) << cBox[6] << "|" << cBox[7] << "|" << cBox[8] << endl;
}
}
// Function definiton to keep score
int score(size_t PlayerMove)
{
int static score1{ 1 };
int static score2{ 1 };
if (PlayerMove % 2)
return score1++;
else
return score2++;
}
// Function definiton to print scoreboard
int scoreboard(int score1, int score2)
{
cout << endl << setfill(' ') << setw(47) << "PLAYER 1: " << score1 << " " << "PLAYER 2: " << score2;
return(score1, score2);
}
// Function definiton to throw an error
void error() {
{
cout << setfill(' ') << setw(64) << "Invalid Move. Try again." << endl;
cin.clear(); //clear the error flags.
cin.ignore(); //sync up the stream in case the user entered white space
}
}
// Function definiton to end game
void GameOver()
{
EndGame = true;
}
#include <iostream>
using namespace std;
int main()
{
char num[10];
int a;
cout << "Odd or Even"<< endl;
for(;;)
{
cout << "Enter Number:" ;
cin >> num;
cout << endl;
for(a=9;a>=0;a--)
{
if(num[a]!='\0 && num[a]!=' ')
break;
}
if(num[a]==1 || num[a]==3 || num[a]==5 || num[a]==7 || num[a]==9)
cout << "Odd" << endl;
else
cout << "Even" << endl;
}
}
I am a rookie of C++,and I wrote a program to discriminate if a number is even or odd,
but no matter what number I enter, it only outputs "Even".
So I added these to find out when did the loop breaks:
cout << a << endl;
cout << "\"" << num[a] << "\"" << endl;
Result:
Enter Number:11
9
" "
Even
the for loop beraks when num[9]=' '? Which will lead to else and always output "Even".
You are confused about the character '1' and the number 1. They are different.
Instead of
if(num[a]==1 || num[a]==3 || num[a]==5 || num[a]==7 || num[a]==9)
you need
if(num[a]=='1' || num[a]=='3' || num[a]=='5' || num[a]=='7' || num[a]=='9')
Update
There is one more problems that is probably tripping you up.
num is not initialized. Zero-initialize it. Remember 0 is not the same as the character '0'.
char num[10] = {0};
Move the initialization of num inside the for loop. That will eliminate the problem of data from a previous execution of the loop from affecting the current execution of the loop.
Here's a version that works for me.
#include <iostream>
using namespace std;
int main()
{
cout << "Odd or Even"<< endl;
for(;;)
{
char num[10] = {0};
int a;
cout << "Enter Number:" ;
cin >> num;
cout << endl;
for(a=9;a>=0;a--)
{
if(num[a]!='\0' && num[a]!=' ')
break;
}
cout << num[a] << endl;
if(num[a]=='1' || num[a]=='3' || num[a]=='5' || num[a]=='7' || num[a]=='9')
cout << "Odd" << endl;
else
cout << "Even" << endl;
}
}
PS
You can replace the line
if(num[a]!='\0' && num[a]!=' ')
by
if(isdigit(num[a]))
That makes more sense to me.
If you are doing this with c++ there are much easier ways! Consider the following:
while (!done) {
string inputline;
getline(cin, inputline); //Now we have a string with the users input!
stringstream ss; // stringstreams help us parse data in strings!
int num; // We have a number we want to put it into.
ss >> num; // We can use the string stream to parse this number.
// You can even add error checking!
// Now to check for odd even, what do we know about even numbers? divisable by 2!
if (num % 2 == 0) // No remainder from /2
cout << Even << '\n'
else
cout << Odd << '\n'
}
see how you go with that!
Warning Untested code
You did a mistake (typo) here in this line..
if(num[a]!='\0 && num[a]!=' ')
it should be
if(num[a]!='\0' && num[a]!=' ')
I have one of those basic assignments where you need to count the numbers of specific types of characters in an input file. There are 3 files involved, the main program (which I will include below), the hopper.txt input text to be analyzed, and the sample output.txt which demonstrates what the output should look like in the command line.
I believe I have everything set but my final numbers arnt turning out correctly. Specifically, my other and total counters are about 200 over. Now I've done some counting with other programs and am pretty sure that the sample output is correct which is why I suspect that I must be counting the hidden characters (and they must be there because the output isn't just a block of text).
I've tried casting each character to an int in order to see what its ascii value is and go off of that range but my IDE (Xcode) says that "comparison of constant with expression of type 'bool' is always true", and the check doesn't seem to catch anything.
Here are the other two files:
hopper.txt
sample output.txt
/***************************************************************
CSCI 240 Program 4 Summer 2013
Programmer:
Date Due: 7/14/14
Purpose: This program reads in the characters from a text file.
While reading them it takes cultivates relivant data about
the frequency of different ascii characters and shares its
results.
***************************************************************/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <unistd.h>
#define FILENAME "/Users/username/Documents/NIU/240/Assigntment\ 4/hopper.txt"
using namespace std;
bool isVowel(char ch);
bool isConsonant(char ch);
int main()
{
ifstream inFile;
inFile.open (FILENAME, ios::in);
char ch;
int t_total = 0;
int t_vowel = 0;
int t_consonant = 0;
int t_letter = 0;
int t_leftParen = 0;
int t_rightParen = 0;
int t_singleQuote = 0;
int t_doubleQuote = 0;
int t_digit = 0;
int t_other = 0;
//See if we successfully imported the file
if (inFile.fail())
{
cout<< "\nThe file entitled: " << FILENAME << " failed to open.\n";
return 0;
}
do
{
//get next letter and print it out
inFile.get (ch);
cout << ch;
//increment total
t_total++;
//check if the character is a letter and if so if it is a vowel or consonant
if(isalpha(ch)){
t_letter++;
//we have found a letter
if(isVowel(ch)) {
t_vowel++;
//we have found a vowel
}
else if(isConsonant(ch)) {
t_consonant++;
//we have found a consonant;
}
else {
cout << "\nYou shouldnt be here...";
}
}
//check if the character is a digit
else if (isdigit(ch)) {
t_digit++;
//we have found a digit
}
//filter out formating characters
else if (!( 32 <= ((int)ch) <= 255)) {
continue;
}
//covers all other cases of askii characters
else {
switch(ch) {
case '(':
t_leftParen++;
break;
case ')':
t_rightParen++;
break;
case '\'':
t_singleQuote++;
break;
case '\"':
t_doubleQuote++;
break;
default:
t_other++;
break;
}
}
} while (inFile);
//These are really just here for the convience of not changing each value while working on formatting
int width1 = 25;
int width2 = 6;
//print out the totals found in the document
cout << "\n\nSummary\n";
cout << fixed << setw(width1) << "\nTotal characters:" << setw(width2) << right << t_total;
cout << fixed << setw(width1) << "\nVowels:" << setw(width2) << right << t_vowel;
cout << fixed << setw(width1) << "\nConsonants:" << setw(width2) << right << t_consonant;
cout << fixed << setw(width1) << "\nLetters:" << setw(width2) << right << t_letter;
cout << fixed << setw(width1) << "\nDigits:" << setw(width2) << right << t_digit;
cout << fixed << setw(width1) << "\nLeft parentheses:" << setw(width2) << right << t_leftParen;
cout << fixed << setw(width1) << "\nRight parentheses:" << setw(width2) << right << t_rightParen;
cout << fixed << setw(width1) << "\nSingle quotes:" << setw(width2) << right << t_singleQuote;
cout << fixed << setw(width1) << "\nDouble quotes:" << setw(width2) << right << t_doubleQuote;
cout << fixed << setw(width1) << "\nOther:" << setw(width2) << right << t_other;
return 0;
}
/***************************************************************
Function: isVowel
Use: Checks if the inputed character is a vowel.
Arguements: 1. ch: A askii character
Returns: true if it is a vowel, false if it is not
***************************************************************/
bool isVowel(char ch) {
//double check we have a letter
if(isalpha(ch)) {
//reduce to lower case to reduce the number of cases that must be checked
ch = tolower(ch);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
return true;
}
else {
return false;
}
}
return false;
}
/***************************************************************
Function: isConsonant
Use: Checks if the inputed character is a consonant.
Arguements: 1. ch: A askii character
Returns: true if it is a consonant, false if it is not
***************************************************************/
bool isConsonant(char ch) {
//So long as it is a letter, anything that is not a vowel must be a consonant
if(isalpha(ch)) {
return !isVowel(ch);
}
return false;
}
You can use std::isspace to test if a character is one of :
space (0x20, ' ')
form feed (0x0c, '\f')
line feed (0x0a, '\n')
carriage return (0x0d, '\r')
horizontal tab (0x09, '\t')
vertical tab (0x0b, '\v')
And ignore those by adding a test in your reading loop :
else if (std::isspace(ch)) {
continue; // Do not update counters
}