I have been working on this all day with no luck. Its night now and don't know what to do. My assignment is to read number of vowels, number of white spaces, and number of other characters in a user inputted sentence. I know i need to use cin.get(ch) for whitespaces, but don't know how. I also need to output the sentence to a file. Heres what I have so far:
//Get data from user
cout << "Enter your sentence on one line followed by a # to end it: " << endl;
while (cin >> noskipws >> character && character != '#')
{
character = static_cast<char>(toupper(character));
if (character == 'A' || character == 'E' || character == 'I' ||
character == 'O' || character == 'U')
{
vowelCount++;
isVowel = true;
}
if (isspace(character))
{
whiteSpace++;
}
else if (isVowel == true && isspace(character))
{
otherChars++;
}
outFile << character;
}
outFile << "vowelCount: " << vowelCount << endl;
outFile << "whiteSpace: " << whiteSpace << endl;
outFile << "otherchars: " << otherChars << endl;
This line
if (character == 'A' || 'E' || 'I' || 'O' || 'U');
Is not doing what you think. It will always return true.
you need
if (character == 'A' || character == 'E' || character == 'I' || character == 'O' || character =='U')
and remove the semicolon as well at the end of that line
Here:
while (cin >> character && character != '#')
You are skipping all white space. To prevent the operator >> from skiiping white space you need to explicitly specify this with the noskipws modifier.
while(std::cin >> std::noskipws >> character && character != '#')
Alternatively the same affect can be achieved with get
while(std::cin.get(character) && character != '#')
Next you are reading more characters outside the loop condition.
cin.get(character);
You already have a value in the variable 'character'. So remove both of these. The next iteration of the loop (in the while condition) will get the next character (as it is executed before the loop is entered).
Then fix you test as Tim pointed out.
You can then add another test for white space with:
if (std::isspace(character)) // Note #include <cctype>
{ /* STUFF */ }
#include <iostream>
using namespace std;
int main()
{
char ch;
int vowel_count = 0;
int space_count = 0;
int other_count = 0;
cout << "Enter a string ends with #: " << endl;
while(1)
{
cin.get(ch);
if(ch == '#')
{
break;
}
if(ch == 'A' || ch == 'a'
|| ch == 'E' || ch == 'e'
|| ch == 'I' || ch == 'i'
|| ch == 'O' || ch == 'o'
|| ch == 'U' || ch == 'u')
{
++vowel_count;
}
else if(ch == ' ')
{
++space_count;
}
else
{
++other_count;
}
}
cout << "Vowels: " << vowel_count << endl;
cout << "White spaces: " << space_count << endl;
cout << "Other: " << other_count << endl;
return 0;
}
No arrays
You can check for whitespace the exact same way. Common whitespace characters are space (' '), and horizontal tab ('\t'). Less-common are newline ('\n'), carriage return ('\r'), form feed ('\f') and vertical tab ('\v').
You can also use isspace from ctype.h.
Related
I just want to read every character in a file where I put characters from A TO Z but the program prints A every time and count vowels 4 and character 25 but expectation was to printing vowels 5 and characters 26 how to fix this program fixing from last 4 hours but nothing progress?
Code:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
int i, count = 0, vowel_count = 0;
string file_name;
cout << "enter file name:";
cin >> file_name;
ifstream fin;
fin.open(file_name);
char ch;
while (!fin.eof()) {
fin.get(ch);
cout << ch;
while (fin >> ch) {
i = ch;
if ((i > 63 && i < 91) || (i > 96 && i < 123))
count++;
if (i == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
vowel_count++;
}
cout << "\n No. of Characters in a File : " << count;
cout << "\n No. of vowel characters in the File : " << vowel_count;
}
fin.close();
return 0;
}
You have some really minor erros in the code, which I fixed for you.
Additionally, I added a check, if the file could be opened or not. That is the problem in most cases.
Please see below:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
int count = 0, vowel_count = 0;
string file_name;
cout << "\nEnter file name: ";
cin >> file_name;
ifstream fin(file_name);
if (fin) {
char ch;
while (fin.get(ch)) {
cout << ch;
if ((ch >= 'A' && ch <= 'Z') || (ch > 'a' && ch <= 'z'))
count++;
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
vowel_count++;
}
fin.close();
cout << "\n No. of Characters in a File : " << count;
cout << "\n No. of vowel characters in the File : " << vowel_count;
}
else std::cerr << "\n\n*** Error. Could notopen '" << file_name << "'\n\n";
return 0;
}
basically I am having weird trouble with my while loop near the beginning of the program which checks for user validation on their choice of activity. When they choose the first activity and complete it, it works fine, but when they complete the second activity, it will go into runtime and keep requesting the user to input a valid choice, even though they haven't even gotten the chance to input a choice. Any tips?
#include <iostream>
using namespace std;
int main()
{
const int DIGITS_CHOICE = 1, IDENTIFIER_CHOICE = 2, DOUBLE_CHOICE = 3, EXIT_CHOICE = 4;
int choice;
int userNumber, storedNumber, factor = 10, digitCounter = 0, subtractor;
char ch;
do
{
cout << "\n\n\t\tPlease choose an option:\n\n"
<< "1. How many digits?\n"
<< "2. Is this a valid C++ Identifer?\n"
<< "3. Is this a double letter word?\n"
<< "4. Exit\n";
cout << endl << "Choice: ";
cin >> choice;
while (choice < DIGITS_CHOICE || choice > EXIT_CHOICE)
{
cout << endl << "Please enter a valid menu option: ";
cin >> choice;
}
if (choice != EXIT_CHOICE)
{
switch (choice)
{
case DIGITS_CHOICE:
cout << "Please enter an integer: ";
cin >> userNumber;
storedNumber = userNumber;
if (userNumber < 10)
{
digitCounter = 1;
}
else
{
while (userNumber != 0)
{
subtractor = userNumber % factor;
if (subtractor > 0)
{
userNumber = userNumber - subtractor;
factor *= 10;
digitCounter++;
}
else
{
userNumber = 0;
}
}
}
cout << storedNumber << " has " << digitCounter << " digit(s)." << endl;
factor = 10;
digitCounter = 0;
break;
case IDENTIFIER_CHOICE:
cout << "Please enter an identifier and press [Enter] immediately after. ";
cin >> ch;
if (ch >= 0 || ch <= 9 || ch <= 'a' || ch >= 'z' || ch <= 'A' || ch >= 'Z' || ch != '_')
{
if (ch >= 0 || ch <= 9)
{
cout << "Not a valid identifier." << endl;
cout << "Identifiers cannot start with a digit." << endl;
ch = '\n';
}
else
{
cout << "Not a valid identifier." << endl;
cout << "Inavlid character." << endl;
ch = '\n';
}
}
while (ch != '\n')
{
if (ch >= 'a' || ch <= 'z' || ch >= 'A' || ch <= 'Z')
{
cin.get(ch);
}
}
break;
case DOUBLE_CHOICE:
break;
}
}
} while (choice != EXIT_CHOICE);
return 0;
}
Also the program isn't complete yet. the third option has nothing and the 2nd option is almost complete. the first activity though is complete :)
Your check for valid characters is too broad, and doesn't really make sense:
if (ch >= 0 || ch <= 9 || ch <= 'a' || ch >= 'z' || ch <= 'A' || ch >= 'Z' || ch != '_')
Every possible value of ch is going to be greater than or equal to zero, so this expression is equivalent to (true || a || b || c || ... || z) and it's always going to resolve to true.
Instead, see if it's below 'A', between 'Z' and 'a' or beyond 'z' and if so, it's invalid.
Also, when checking if it's a digit, you need to check if it's ≥ '0' and ≤ '9' as characters. It's important that you compare it to the character representation of 0 and 9 because the value of the character '0' not actually 0 (it turns out it's actually 48) and likewise with '9':
if ( ch < 'A'
|| (ch > 'Z' && ch < 'a')
|| ch > 'z')
{
if (ch >= '0' && ch <= '9')
{
cout << "Not a valid identifier." << endl;
cout << "Identifiers cannot start with a digit." << endl;
ch = '\n';
}
else
{
cout << "Not a valid identifier." << endl;
cout << "Invalid character." << endl;
ch = '\n';
}
}
It's not really clear what the check after that is meant to do? Is it only meant to allow letters? That seems strange after saying "Identifiers cannot start with a digit." anyway:
if (ch >= 'a' || ch <= 'z' || ch >= 'A' || ch <= 'Z')
This has essentially the same issue where every character is going to be either above 'a' or below 'z' or both, so this will always resolve to true. Instead, use && to check for being within a range:
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
Hopefully that addresses your question.
The logic is not great; i is valid, but your code says it's not. It at least goes back to the menu just fine. Your code is also behaving like it will respond immediately as letters are being typed. That is not the case. It won't print anything until the user presses Enter.
It seems the issue is your variable ch being a char. If I type anything that's longer than a single character, what will happen is that the single character gets evaluated, and the remaining characters I typed remain in the input stream. It looks like you are attempting to handle that, but it's not working. I am not going to spend time delving into the why, partly because it's complex, partly because I don't know the full intricacies of istream behavior.
What I will say is that if you want to handle a multi-character input, use cin.get() everywhere and not just sometimes. You can do processing of each character, but again, nothing will go to the screen until the user presses Enter.
But here's code that appears to work:
#include <cctype> // isalpha() and isalnum()
#include <string> // ch is now a std::string
// ...
case IDENTIFIER_CHOICE:
cout << "Please enter an identifier and press [Enter] immediately after. ";
std::cin.ignore(256, '\n'); // needed because of getline behavior
std::getline(std::cin, ch);
if (!(isalpha(ch[0]) || ch[0] == '_')) {
cout << "Not valid.\n";
break;
}
for (int i = 1; i < ch.size(); ++i) {
if (!isalnum(ch[i])) {
cout << "Not valid.\n";
break;
}
}
cout << "Valid.\n";
break;
// ...
With cin, when you press Enter, that keystroke is saved in the input stream. getline() doesn't behave the way we expect because while cin will typically ignore that keystroke, getline does not. So I just tell cin to ignore an arbitrary (but sufficient in this case) amount of characters in the stream up to and including the Enter keystroke (Mac and Linux, should still behave for Windows (I think)).
This is still far from bulletproof input validation (that's impossible), but I think it suffices for what you're working on.
This code is replacing all the characters. Not just vowels. What am I doing wrong?
using namespace std;
bool isVowel(char);
int main() {
string fName = "";
string lName = "";
cout << "Enter first name: " << endl;
cin >> fName;
cout << "Enter last name: " << endl;
cin >> lName;
string name = fName + " " + lName;
cout << name << endl;
for(int i = 0; i < name.length(); i++) {
if(isVowel(name.at(i))) {
name[i] = 'z';
}
}
cout << name << endl;
}
bool isVowel(char c) {
if(c == 'a' || 'e' || 'i' || 'o' || 'u' || 'A' || 'O' || 'E' || 'I' || 'U') {
return true;
}
else {
return false;
}
}
I did some research online and I think my problem lies in that I am passing the character as a reference? I didn't understand how that could be...
The isVowel() function checks if the char is a vowel I think that's where the problem lies, since the program is replacing all the characters I'm assuming that function is not working.
you need to put your if statement as (c == 'a' || c == 'e' || c == 'i'..., the way it is written currently it casts all of the characters on their own as boolean expressions.
I am taking a college level C++ course, and quite frankly nothing is really ever explained. I was given code to write, and my program works as it should. I would just like to know the purpose of certain lines.
Such as:
int i = 0;
I know I am declaring an int variable that = 0. Here my question is why the letter i? Could that be any variable name I choose?
int length = input.length();
I know I am declaring an int variable named length... but what purpose does it serve in my code?
i++
I think this ends my loop?
I have added my code for perusal. Any assistance would be greatly appreciated!
// Program takes user entered letter and matches it with the corresponding ICAO word.
//Program has been modified to use void and string methods
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
//Function Heading
void convert(string);
//Main Function
int main()
{
string input;
cout << " Enter a letter or word: "; // Ask the user to enter a letter or word.
cin >> input; //get input
cout << "Phonetic Version : "; //Display "Phonetic Version"
convert (input);
cout << endl;
system("pause");
}//End Main
//Function Definition
void convert(string input)
{
int i = 0; //input variable
char letters; //character variable
int length = input.length();
while (i < length) //While loop initialized
{
letters = input.at(i);
if (letters == 'a' || letters == 'A')
cout << "Alpha ";
else if (letters == 'b' || letters == 'B')
cout << "Bravo ";
else if (letters == 'c' || letters == 'C')
cout << "Charlie ";
else if (letters == 'd' || letters == 'D')
cout << "Delta ";
else if (letters == 'e' || letters == 'E')
cout << "Echo ";
else if (letters == 'f' || letters == 'F')
cout << "Foxtrot ";
else if (letters == 'g' || letters == 'G')
cout << "Golf ";
else if (letters == 'h' || letters == 'H')
cout << "Hotel ";
else if (letters == 'i' || letters == 'I')
cout << "India ";
else if (letters == 'j' || letters == 'J')
cout << "Juliet ";
else if (letters == 'k' || letters == 'K')
cout << "Kilo ";
else if (letters == 'l' || letters == 'L')
cout << "Lima ";
else if (letters == 'm' || letters == 'M')
cout << "Mike ";
else if (letters == 'n' || letters == 'N')
cout << "November ";
else if (letters == 'o' || letters == 'O')
cout << "Oscar ";
else if (letters == 'p' || letters == 'P')
cout << "Papa ";
else if (letters == 'q' || letters == 'Q')
cout << "Quebec ";
else if (letters == 'r' || letters == 'R')
cout << "Romeo ";
else if (letters == 's' || letters == 'S')
cout << "Sierra ";
else if (letters == 't' || letters == 'T')
cout << "Tango ";
else if (letters == 'u' || letters == 'U')
cout << "Uniform ";
else if (letters == 'v' || letters == 'V')
cout << "Victor ";
else if (letters == 'w' || letters == 'W')
cout << "Whiskey ";
else if (letters == 'x' || letters == 'X')
cout << "X-ray ";
else if (letters == 'y' || letters == 'Y')
cout << "Yankee ";
else if (letters == 'z' || letters == 'Z')
cout << "Zulu ";
i++;
}
}
int length = input.length();
I know I am declaring an int variable named length... but what purpose
does it serve in my code?
None.
It would serve some purpose if input's length would change later on and you'd need to remember the old length for some reason.
Since this is not the case here, your professor may think that this is some kind of "optimisation" on the grounds that repeatedly calling length() may be too slow. But this is nonsense; your computer is too fast for such micro-optimisations to have an observable effect, especially with modern compilers being much better at optimising programs than the programmers themselves.
Just remove the length variable to make the code shorter.
Here
string input;
std::string has a method called length() which returns the length of the string, in terms of bytes. Hence you are using like
int length = input.length(); /* use variable name as other than predefined method to avoid confusion */
| |
this is just this is a method of string
a int variable
int i = 0;
I know I am declaring an int variable that = 0. Here my question is why the letter i? Could that be any variable name I choose?
Yes. Variable names are arbitrary, name them however you want (within the restrictions of the language syntax, of course). Just make sure you use names that are meaningful within the context in which they are being used. Readability matters when maintaining code over time.
int length = input.length();
I know I am declaring an int variable named length... but what purpose does it serve in my code?
To make a local cached copy of the character count of the input string so your loop does not have to keep calling the string's length() method over and over. Using a few bytes of local stack space can save time and overhead of retrieving the string's length, which does not change while the loop runs.
i++
I think this ends my loop?
It increments the value of the i variable, nothing more. The loop ends when the while statement evaluates as false (when i catches up to length).
#include <iostream>
using namespace std;
char firstLetter;
int pigLatin();
string word;
int wordFinder();
int firstVowel;
int x;
char vowel = ('a' && 'e' && 'i' && 'o' && 'u' && 'y' && 'A' && 'E' && 'I' && 'O' && 'U' && 'Y');
string engSentence;
char* letter = &engSentence[0];
bool vowelChecker (char c) // will check to see if there is a vowel
{
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' || c == 'Y')
{
return true;
}
else
{
return false;
}
}
int pigLatin()
{
int lastLetter = word.length();
firstLetter = word[0];
if (vowelChecker(firstLetter)) //if the first letter of a word is a vowel...
{
cout << word << "way "; // print the word then way
}
else //if the first letter is not a vowel...
{
for (x = 1; x < lastLetter; x++) //in the loop of starting at the second letter and going to the last letter...
{
if (vowelChecker(x)) // check each letter to see if there is a vowel...
{
int firstVowel = x; //says that the first vowel is at point x
break;
}
}
string firstPortion = word.substr(0, firstVowel);
string secondPortion = word.substr(firstVowel, lastLetter);
cout << secondPortion << firstPortion << "ay";
//above is stating that it will first print the part of the word from the first vowel to the last letter,
//then it will print from the first letter to the first vowel and add 'ay' to the end
}
return 0;
}
int wordFinder() //will find words within a string
{
char* letter = &engSentence[0];
while ( *letter != '\0') //while the string isn't done...
{
if ( *letter == ' ' || *letter == '.' || *letter == ',' || *letter == '-' || *letter == '!' || *letter == '?') //if there is a space, comma or period...
{
pigLatin(); //run piglatin func
cout << " "; // add a space before the next word
word = ""; //sets the word back to empty
}
else
{
word += *letter; //adds letters to the word if no space comma or period is found.
}
letter++;
}
return 0;
}
int main()
{
cout << "Please enter a sentence for me to translate: " << endl;
cout << "**REMEMBER TO END SENTENCES WITH A PERIOD OR QUESTION MARK OR EXPLANATION MARK!**" << endl;
getline(cin, engSentence); //will get the whole line entered
wordFinder(); //runs wordfinder function
}
So far, it will only work for if the vowel is the first letter. ( if (vowelChecker(firstLetter)) { cout << word << "way ";} ) this portion of the text... The other part seems to not being ran through in the Piglatin Function. Also I'm Getting a warning that says that firstVowel isn't being used, which would explain why my program isn't running correctly. Not sure why though...
if (vowelChecker(x)) // check each letter to see if there is a vowel...
this is passing the loop variable x, not the character at that position. What you want is:
if (vowelChecker(word[x])) // check each letter to see if there is a vowel...