The problem is to find all vowels all even words in a sentence share, in other words these vowels have to be met in any even word in the sentence.
But i when i enter for example: "ewedyua aiuye dswidje ieuayj eeee eeeui dajhdfjcne aodijsbfe".
I get: e i u
but "e i" is expected as the last even word doesn't contain 'u' (I use " " just for separation here in the text and don't use them in the output)
The program:
int main(){
string str;
char ch = ' ';
set<char> strSet;
set<char> resultSet;
set<char> tempSet;
int count = 1;
int i = 0;
cout << "Enter a line: ";
getline(cin, str);
str = delOverSpace(str); // delete excessive gaps<br>
do {
ch = str.at(i);
if(((count % 2) == 0) && (ch != ' ')){ // this is an even word and not a gap
if(isVowel(upperToLower(ch))) // this is a vowel
tempSet.insert(upperToLower(ch));
}
if (ch == ' ') { // if we've passed through the word add inforamtion on it
if(((count % 2) == 0) && (count / 2) == 1)
strSet.insert(tempSet.begin(), tempSet.end());
else if (((count % 2) == 0) && (count / 2) != 1){
set_intersection(
strSet.begin(),strSet.end(), tempSet.begin(), tempSet.end(),
insert_iterator<set<char> >(resultSet, resultSet.begin())
);
strSet.clear();
tempSet.clear();
strSet.insert(resultSet.begin(), resultSet.end());
resultSet.clear();
}
count++;
}
i++;
}while(ch != '.');
if (count == 2) cout << "Only one word was entered" << endl;
else if (strSet.empty()) cout << "No vowels were found" << endl;
else {
copy(strSet.begin(), strSet.end(), ostream_iterator<char>(cout, " "));
cout << endl;
}
return 0;
}
Try not to use one counter variable for multiple purposes.
For example you could use count for the current character count within the current word and words for word count.
In your example, you're making count work too hard.
Decide what you are counting. Do you want to count every character?
Or do you want to count the characters in the current word?
When incrementing a counter, try to put this next to the logic that needs it.
Eg, i++ should go right after you've used it to get the next character.
And count should be incremented in the block that handles letters (ie not space, not dot).
If the counters get too far away from what they are keeping track of, you can introduce bugs.
Move the space check up first and also check for end of sentence with .
Clear indentation helps to follow the code - I use 4 characters, but 2 or 3 is ok.
1 character indents are hard to read.
Use blank lines to separate different chunks of logic.
You might want to add logic to handle punctuation like ,, ?, ! etc.
When you're processing an input string which is separated into words, it's often easier to handle the end of input condition outside the loop.
In this case, the loop exits after it picks up the last letter.
If that is not a . then you'll have an unprocessed word sitting in tempSet.
You can try and anticipate this within the loop, but it seems more natural to exit the loop and check if there is anything left to process.
If you separate your logic into clearly separated blocks, you can set breakpoints inside each block.
You'll then know what situation you're handling. You can break inside end-of-word logic and check tempSet and count.
Are they what you expect?
And in the else part you can check ch going in and verify that it is classified as a vowel properly.
int main() {
string str;
char ch = ' ';
set<char> strSet;
set<char> tempSet;
int count = 0, words = 0, i = 0;
cout << "Enter a line: ";
getline(cin, str);
str = delOverSpace(str); // delete excessive gaps<br>
while ( i < str.size() && ch != '.' ) {
// Get next character
ch = str.at(i);
i++;
if (ch == ' ' || ch == '.' ) { // if we've passed through the word add inforamtion on it
if( count > 0 && ((count % 2) == 0)) {
strSet.insert(tempSet.begin(), tempSet.end());
words++;
}
count = 0; // reset the char counter
tempSet.clear(); // clear the temp vowel set
}
else {
// letter - not a space or a dot, increase the character count
count++;
if(isVowel(upperToLower(ch))) // this is a vowel
tempSet.insert(upperToLower(ch));
}
}
// pick up any unprocessed word if we hit end of input without seeing '.'
if (count > 0 && ((count % 2) == 0)) {
strSet.insert(tempSet.begin(), tempSet.end());
words++;
}
if (words == 0)
cout << "No words entered" << endl;
else if (words == 1)
cout << "Only one word was entered" << endl;
else if (strSet.empty())
cout << "No vowels were found" << endl;
else {
copy(strSet.begin(), strSet.end(), ostream_iterator<char>(cout, " "));
cout << endl;
}
return 0;
}
Related
I need to write a sentence in Pig Latin form and I am almost done it successfuly except for 1 case and I almost give up
for example :
If my word starts at a\e\o\u\i the word will look like easy -> easyway , apple -> appleway
and if it doesnt start with a letter that I wrote above
it will look like that: box -> oxbay , king -> ingkay
I succeed with the bolded part but in the first part with a\e\o\u\i letter at the beginning , I dont know where to put the w before and need some help with it
This is my code , thanks in advance
#include <iostream>
//Since those are used in ALL function of program, it wont hurt to set it to global
//Else it is considered EVIL to declare global variables
const int maxLine = 100;
char phraseLine[maxLine] = { '\0' };
void pigLatinString();
using namespace std;
void main()
{
// Displayed heading of program
cout << "* You will be prompted to enter a string of *" << endl;
cout << "* words. The string will be converted into *" << endl;
cout << "* Pig Latin and the results displayed. *" << endl;
cout << "* Enter as many strings as you would like. *" << endl;
//prompt the user for a group of words or press enter to quit
cout << "Please enter a word or group of words. (Press enter to quit)\n";
cin.getline(phraseLine, 100, '\n');
cout << endl;
// This is the main loop. Continue executing until the user hits 'enter' to quit.
while (phraseLine[0] != '\0')
{
// Display the word (s) entered by the user
cout << "You entered the following: " << phraseLine << endl;
// Display the word (s) in Pig Latin
cout << "The same phrase in Pig latin is: ";
pigLatinString();
cout << endl;
//prompt the user for a group of words or press enter to quit
cout << "Please enter a word or group of words. (Press enter to quit)\n";
cin.getline(phraseLine, 100, '\n');
}
return;
}
void pigLatinString() //phraseLine is a cstring for the word, maxline is max length of line
{ //variable declarations
char tempConsonant[10];
tempConsonant[0] = '\0';
int numberOfConsonants = 0;
char previousCharacter = ' ';
char currentCharacter = ' ';
bool isInWord = 0;
// for loop checking each index to the end of whatever is typed in
for (int i = 0; i < maxLine; i++)
{
//checking for the end of the phraseline
if (phraseLine[i] == '\0')
{//checking to see if it's in the word
if (isInWord)
{//checking to see that there wasn't a space ahead of the word and then sending the cstring + ay to the console
if (previousCharacter != ' ')
cout << tempConsonant << "ay" << endl;
}
return;
}
// this covers the end of the word condition
if (isInWord)
{// covers the condition of index [i] being the space at the end of the word
if (phraseLine[i] == ' ')
{
// spits out pig latin word, gets you out of the word, flushes the temp consonants array and resets the # of consonants to 0
cout << tempConsonant << "ay";
isInWord = 0;
tempConsonant[0] = '\0';
numberOfConsonants = 0;
}
cout << phraseLine[i] ;
}
else
{//this covers for the first vowel that makes the switch
if (phraseLine[i] != ' ')
{// sets the c string to what is in the phraseline at the time and makes it capitalized
char currentCharacter = phraseLine[i];
currentCharacter = toupper(currentCharacter);
// this takes care of the condition that currentCharacter is not a vowel
if ((currentCharacter != 'A') && (currentCharacter != 'E') &&
(currentCharacter != 'I') && (currentCharacter != 'O') && (currentCharacter != 'U'))
//this sets the array to temporarily hold the consonants for display before the 'ay'
{//this sets the null operator at the end of the c string and looks for the next consonant
tempConsonant[numberOfConsonants] = phraseLine[i];
tempConsonant[numberOfConsonants + 1] = '\0';
numberOfConsonants++;
}
else
{// this sets the boolean isInWord to true and displays the phraseline
isInWord = 1;
cout << phraseLine[i];
}
}
else
{
cout << phraseLine[i] ;
}
}
previousCharacter = phraseLine[i];
}
return;
}
You have two conditions to consider. if your word starts with a vowel, just add "way" to the end of the word, else move the first letter and add "ay" to the end.
This is a task that can be made a lot simpler by using std::string instead of C-strings. This is because you are now no longer concerned with exceeding your length or losing the null character. It also allows easier access to the Standard Library algorithms.
#include <algorithm>
#include <iostream>
#include <string>
std::string make_pig_latin(const std::string& word) {
std::string vowels("aeiou");
std::string newWord(word);
if (newWord.find_first_not_of(vowels) == 0) {
// Word starts with a consanant
std::rotate(newWord.begin(), newWord.begin() + 1, newWord.end());
newWord += "ay";
} else {
newWord += "way";
}
return newWord;
}
int main() {
std::cout << make_pig_latin("apple") << '\n'
<< make_pig_latin("box") << '\n'
<< make_pig_latin("king") << '\n'
<< make_pig_latin("easy") << '\n';
}
The function above highlights how you can go about structuring your conversion. You just need to know if your word starts with a vowel or not, and take the appropriate action.
Output:
appleway
oxbay
ingkay
easyway
I did not get the impression that you have to care about words like 'phone'.
Looking through your code, you should try to do a better job at separating your concerns. Pig Latin is easier done one word at a time, but you have string splitting code and a lot of "not Pig Latin" code in your Pig Latin function. Your main can handle getting input. You should probably have a separate function to break the line up into individual words, using std::vector to hold the words would be best since it can grow on demand and doesn't have to know a specific capacity up front. You then iterate through your array of words and translate them individually. Depending on what your actual requirements are, it's possible that you don't even have to store the translated words, just print them directly to the screen.
Here's the same program, but now it can separate words. Note how the pig latin function doesn't have to change (much, I added upper-case vowels just because I didn't want to bothered converting words) in order for the added functionality to be added.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
std::string make_pig_latin(const std::string& word) {
std::string vowels("aeiouAEIOU");
std::string newWord(word);
if (newWord.find_first_not_of(vowels) == 0) {
// Word starts with a consanant
std::rotate(newWord.begin(), newWord.begin() + 1, newWord.end());
newWord += "ay";
} else {
newWord += "way";
}
return newWord;
}
int main() {
std::string phrase(
"A sentence where I say words like apple box easy king and ignore "
"punctuation");
std::istringstream sin(phrase);
std::vector<std::string> words(std::istream_iterator<std::string>(sin), {});
for (auto i : words) {
std::cout << make_pig_latin(i) << ' ';
}
}
Output:
Away entencesay hereway Iway aysay ordsway ikelay appleway oxbay easyway ingkay andway ignoreway unctuationpay
I have created a program to count the syllables in a word inputted by the user. The user is to enter any amount of words followed by the enter key until the (#) key is entered, then the program is to display the words in a table followed by the syllable count for each word.
I am having issues with the "silent e" portion of my program.
if (word_length - 1 == 'e')
{
vowels = vowels - 1;
It seems as though it is not able to pick up the last letter in the string of words. I have tried to move some of the if statements around to see if that helps and to better identify where the problem lies, and from what I have noticed, as stated earlier i believe it to be with the silent e portion of the code.
It is difficult to find even the smallest errors in my code, so I am asking for another set of eyes to gaze over my code.
Any help will be greatly appreciated.
Also, I have yet to complete the formatting of my results table, so please over look that.
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
string word_1 = "create list";
int vowels = 0;
int word_length; // better to set .length() into variable to eliminate warnings
int words_to_print = 0; // this will count how many words to print to use in for loop later
/*
vector <variable type> name_of_vector[size of vector];
creating vectors
leaving them empty for now
*/
vector <string> words_saved;
vector <int> number_of_syllables_saved;
cout << "Enter 4 words from the English dictionary, to determine the amount of syllables each word has." << endl;
cout << "Please enter [#] when finished, to create a list." << endl;
cin >> word_1;
while (word_1 != "#") // as long as user doesnt enter # you can enter a word and
{ // have it run thru the syllable logic
word_length = word_1.length();
words_to_print++;
words_saved.push_back(word_1);
// ^ this saves the word into the next availabe index of vector for strings.
for (int i = 0; i < word_length ; i++) // length is a variable now instead of function syntax this
{ // eliminates the <: signed/usnsigned mismatch warning below
if ((word_1[i] == 'a') || (word_1[i] == 'e') || (word_1[i] == 'i') || (word_1[i] == 'o') || (word_1[i] == 'u') || (word_1[i] == 'y'))
{
vowels = vowels + 1;
if ((word_1[i + 1] == 'a') || (word_1[i + 1] == 'e') || (word_1[i + 1] == 'i') || (word_1[i + 1] == 'o') || (word_1[i + 1] == 'u') || (word_1[i + 1] == 'y'))
{
vowels = vowels - 1;
if (word_length - 1 == 'e')
{
vowels = vowels - 1;
if (vowels == 0)
{
vowels = vowels + 1;
}
}
}
}
}
number_of_syllables_saved.push_back(vowels);
//^ this puts number of syllables into vector of ints
vowels = 0; // this resets the amounts so it can count vowels of next word and not stack from previous word
cin >> word_1; // this will reset the word and controls loop to print out chart if # is entered
}
// use a for loop to print out all the words
cout << endl << endl << endl;
cout << "Word: " << setw(30) << "Syllables: " << endl;
for (int x = 0; x < words_to_print; x++)
{
cout << words_saved[x] << setw(20) << number_of_syllables_saved[x] << endl;
}
//system("pause");
return 0;
}
You are comparing the character 'e' to the integer word_length - 1 instead of comparing it to the last character of your string as you intended.
You should replace if (word_length - 1 == 'e') with if (word_1[word_length - 1] == 'e').
Your nested if-statements don't get evaluated at the anticipated index.
Say the input is "state".
At i = 0, word_1[i] = 's', doesn't pass the first if statement.
At i = 1, word_1[i] = 't', doesn't pass the first if statement.
At i = 2, word_1[i] = 'a', vowels becomes 1. The program does not proceed further down the nested if statements since word_1[i+1] is 't'.
At i = 3, word_1[i] = 't', doesn't pass the first if statement.
At i = 4, word_1[i] = 'e', vowels becomes 2. The program does not proceed further down the nested if statements since word_1[i+1] is garbage value.
As you can see, it never reaches the nested if-statements as you intended
I'm new to c++ and coding in general and I ran into a bit of an issue in one of my assignments. I'm just looking for some input and hopefully an explanation on why my code isn't working.
I'm trying to get input from a user and use a cin.get() function to count all the characters in that string. I do this because I want to determine the letters in each word of the string. Now my issues are I can't get it to print the result correctly.
My question is: Why can't I get a result when I try to determine if my variable chr is a '\n' character? chr is the variable that hold the value of the current character being read by the cin.get() function) is a '\n'.
I want to be able to update the parameters (word1, word2.....) of my function countWordsByLegth() when the current value of chr is '\n' or in other words the end of the string.
The following code, for example, won't run and it's the only way I know how to update my parameter for a string that contains no spaces (one word strings):
if (counter == 5 && chr == '\n')
{
++word5;
counter =0;
}
Here's my code for reference. The function isWhitespace() just determines if the character is one of the following '\n' , '\r' , '\t'):
while (cin.get(chr) && chr != '\n')
{
counter++;
if (isWhitespace(chr))
{
--counter;
//test = true;
}
if (counter == 5 && chr == '\n')
{
++word5;
counter =0;
}
if (counter == 4 && chr =='\n')
{
++word4;
counter =0;
}
if (counter == 3 && chr =='\n')
{
++word3;
counter =0;
}
if (counter == 2 && chr == '\n')
{
++word2;
counter =0;
}
if (counter ==1 && chr == '\n')
{
++word1;
counter =0;
}
cout << counter << endl; // Test code {delete later}
}
cout << "This is the total of word5: " << word5 << endl;
}
You could use std::string.length() to get the amount of chars in a string.
The length() function returns the number of chars in the string.
#include <iostream>
#include <string>
int main()
{
std::string s;
s = "test";
std::cout << "The string has " << s.length() << " letters!";
}
http://www.cplusplus.com/reference/string/string/ here you can read about the different functions that you can use with strings.
What it's supposed to do
My piglatin program is supposed to take a phrase from user input and output it into pig latin. Basically it would turn a word such as "hello" into "ellohay".
My problem
When I input hello my man the output is ellohay y man an may and when I just input hello my the output is ellohay y may. As you can see, after it translates the first word successfully, it struggles on the second word. It places a space after the y and mayI cannot figure out for the life of me why this keeps happening. The output is even stranger when I input more than two words, as shown above. What I want to happen is for it to output ellohay ymay anmay when I input hello my man. Code is below. Thanks!
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void phrase_Parser(string); // Goes through phrase and looks for ' ' to then pass to pigLatin_Translator()
void pigLatin_Translator(string);
int main()
{
string phrase; //used for user word or phrase to be translated to piglatin
cout << "Enter any word: ";
getline(cin, phrase);
phrase_Parser(phrase);
return 0;
}
void phrase_Parser(string phrase) {
int startCount = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase[i] == ' ') {
string word = phrase.substr(startCount, i);
startCount = (i + 1); // decides where to start the word next time it is ran through
pigLatin_Translator(word); // runs word through translator
}
}
}
void pigLatin_Translator(string word) {
string partOne;
string partTwo;
for (int x = 0; x < word.length(); x++) {
if (word[0] == 'q' && word[1] == 'u') {
cout << word.substr(2, word.length()) << word.substr(0, 2) << "ay ";
break;
}
else if ((word[x] == 'a') || (word[x] == 'e') || (word[x] == 'i') || (word[x] == 'o') || (word[x] == 'u') || (word[x] == 'y')) {
partOne = word.substr(x, word.length()); //from first vowel to end of word
partTwo = word.substr(0, x); // from first letter to first vowel, not including the vowel
cout << partOne << partTwo << "ay "; // adding "ay" to the end of the word
break;
}
}
}
Your problem is in the line string word = phrase.substr(startCount, i);
You are using substr incorrectly. The second argument to substr is the length of the substring you wish to extract. Replace i with i-startCount and you should be good to go.
Alternatively, search for a nicer way to split strings. There are a number of options that are much easier than doing it manually.
im heading several problems in my program, but here is one of them.
I want my code to check if there are two or more underscores in one string next to each other,
example>
lol__lol, lol___lol, etc...
should I do it using while? here is my actual code, which works only for checking when I put underscores like this>
_lol_
so first and last characters are _ and they cant, so it works, because I get output "Chyba - error"
std::string::size_type n;
std::string const ss = slovo;
n = ss.find('_');
// kontrola podtrznika
if ((ss[0] >= 'A' && ss[0] <= 'Z') && ss[1] == '_')
{
cout << "chyba" << endl;
}
if ( !ss.empty() && ss[0] == '_' && ss[ss.length() - 1] == '_' )
{
cout << "chyba" << endl;
}
if ( ss.length() > 3 && ss.find( "__", 1, ss.length() - 2 ) != std::string::npos )
{
cout << "chyba" << endl;
}
if (n == std::string::npos)
{
string s = transform(slovo);
cout << s << endl;
}
else
{
string s = untransform(slovo);
cout << s << endl;
}
Your code seems massively overcomplicated, unless you were misleading in your requirements.
Surely the following is sufficient:
if (slovo.find("__") != slovo.npos) {
// ...
}
It is not clear whether you are going to determine that a string contains within it two or more underscores as for example
"A__B"
or you are going to check whether there is at least two adjacent underscores as for example
"__A" or "A__"
For these two cases two different approaches should be used.
In the second case you simply can use the following call
ss.find( "__" );
In the first case the task is more difficult. At first you should find the first character that is not underscore. Then you need to find the last character that is not underscore and after that apply function find as
ss.find( "__", start_position, length_of_substring );