cannot print a string from a vector of strings - string

I have a vector of strings, and I fill the first string in it manually character by character
vector <std::string> vec(6);
vec[0][0] = 'h';
vec[0][1] = 'e';
vec[0][2] = 'y';
cout << "vec[0] = " << vec[0] << "\n"
now I want to print the vec[0] which is supposed to be a string "hey" , but it prints empty space.
I can print only if I print it character by character also, like this
for(int i = 0 ; i<1 ; i++)
{
for(int j = 0 ; j < 3 ; j++)
{
cout << vec[i][j];
}
cout << "\n";
}
Why I can't simply print the string as a whole.

vector <std::string> vec(6); gives you a vector of six empty strings. vec[0][0] = 'h'; is trying to assign the character h into the first slot of the first empty string, which is not legal, as the bracket operator can only replace existing characters. Use something like vec[0] += 'h' to append to the string.

Related

I need to fix my code to count the syllables of multiple string inputs

As a new student to the C++ language I was originally given the assignment to write a code that would count the amount of syllables in a given string. Later it was changed on me to be able to count multiple strings.Now keep in mind I'm not to far along in the class and honestly I have my concerns about whether or not I'm actually learning what I need to pass this class. So I went back and started the frustrating process of changing my code when it already worked for a different function. I managed to produce the desired format of:
Word Syllable
Harry 2
Hairy 2
Hare 2
The 2
As you can tell it's not correct as it counts the syllables of only the first word and then applies it to the others. I tried changing it to a for loop but it didn't work so I went to a while loop and I got a somewhat better result:
Word Syllable
Harry 2
Word Syllable
Hare 1
So now it correctly counts the syllables but only of every other word instead of all and double prints the table header. Now even my cout command tells me it's ambiguous even though it still runs so I'm extra confused. I'm thinking I might have to change it into an array but at this point I'm completely stumped.
Here is my code so far:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
cout << "Please enter four words: ";
string word;
while (cin >> word);
{
cin >> word;
bool last_vowel = false;
bool last_cons = false;
bool curr_vowel = false;
bool curr_cons = false;
int syllable_count = 0;
for (int i = 0; i < word.length(); i++)
{
string letter = word.substr(i, 1);
if (letter == "a" || letter == "e" ||
letter == "i" || letter == "o" ||
letter == "u" || letter == "y" ||
letter == "A" || letter == "E" ||
letter == "I" || letter == "O" ||
letter == "U" || letter == "Y")
{
curr_vowel = true;
curr_cons = false;
}
else
{
curr_vowel = false;
curr_cons = true;
}
// Increment the syllable count any time we
// transition from a vowel to a consonant
if (curr_cons && last_vowel)
{
syllable_count++;
}
last_vowel = curr_vowel;
last_cons = curr_cons;
}
// Check the last letter in word.
string last = word.substr(word.length() - 1, 1);
// Add one for an ending vowel that is not an "e"
if (last == "a" || last == "i" || last == "o" ||
last == "u" || last == "y" || last == "A" ||
last == "I" || last == "O" || last == "U" ||
last == "Y")
{
syllable_count++;
}
// There has to be at least one syllable
if (syllable_count == 0)
{
syllable_count = 1;
}
cout << left;
cout << setw(10) << "Word" << setw(20) << "Syllables" << endl;
cout << "__________________________" << endl;
cout << left;
cout << setw(19) << word << syllable_count << endl;
}
return 0;
}
Tony answer to your problem is very complicated. I saw someone writing this looks like an unbelievably difficult problem in linguistics while researching the conditions of syllables.
I was not able to find any hard-set rule that can tell you how many syllables are there in the word.
I found some conditions on the program and checked the result to the code on this online tool https://syllablecounter.net/count my guess is they have some list of words to exclude from counting or to be included even if they do not fall under basic conditions.
Wrote the below code to count the syllables in each word of the given phrase.
The program will continue to ask for phrase, Till you enter something other then y when asked to continue.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
while (true) {
cout << "Enter the string you want to count syllable for: ";
string phrase, word;
string vowels = "aeiou";
getline(cin, phrase);
//cout << phrase << endl;
stringstream X(phrase); // Object of stringstream that references the phrase string
// iterate on the words of phrase
while (getline(X, word, ' ')) {
// logic to find syllable in the word.
// Traverse the string
int syllable_count = 0;
// if word[0] in vowels count as syllable
if(vowels.find(tolower(word[0])) != std::string::npos)
syllable_count +=1;
// if word[index] in vowels and word[index - 1] not in vowels count as syllable
for (int i = 1; i < word.size(); i++) {
if(vowels.find(tolower(word[i])) != std::string::npos && vowels.find(tolower(word[i-1])) == std::string::npos)
syllable_count +=1;
}
// if word ends with 'e' it does not cout as syllable
if(tolower(word[word.size()-1]) == 'e')
syllable_count -=1;
// if word ends with 'le' and not of 2 char only and last 3rd word not in vowels it count as syllable
if((word.size() > 2) && (tolower(word[word.size()-1]) == 'e' && tolower(word[word.size()-2]) == 'l' ) && vowels.find(tolower(word[word.size()-3])) == std::string::npos)
syllable_count +=1;
// if word end with 'y' treet it as syllable
if(tolower(word[word.size()-1]) == 'y'){
syllable_count +=1;
// if word end with 'y' and have vowel in last second position count both char as one syllable.
if((word.size() > 2) && vowels.find(tolower(word[word.size()-2])) != std::string::npos)
syllable_count -=1;
}
if(syllable_count == 0)
syllable_count += 1;
cout << word << " : " << syllable_count << endl; // print word and syllable cout
}
cout << "Press y if you want to continue: ";
string stop;
getline(cin, stop);
if( stop != "y")
return 0;
}
return 0;
}
Sample result
Enter the string you want to count syllable for: troy
troy : 1
Press y if you want to continue: y
Enter the string you want to count syllable for: test
test : 1
Press y if you want to continue: y
Enter the string you want to count syllable for: hi how are you
hi : 1
how : 1
are : 1
you : 1
Press y if you want to continue: y
Enter the string you want to count syllable for: Harry hairy hare the
Harry : 2
hairy : 2
hare : 1
the : 1
Press y if you want to continue: n
You might need to add some conditions as you find certain cases. This problem is not something that can be worked with if else only.
Hope this helps.

Code for creating string in a loop to report numbers

I created a code that functions as it is supposed to. I determined the escape function to be -1 for the user to exit the program and used if/else to only add the sum of positive integers.
I know that I have to save the numbers that pass the if statement (only positive numbers) and the only way that I can think of doing this is through a String.
Unfortunately, whenever I attempt to add a string as part of the while loop, it will print the statement over and over again when I only want a single line.
I'm also struggling to set the user input to a single line. I know it has everything to do with the .nextLine() command, but if I pull it outside the brackets (which I've attempted to do) then it reads as an error.
Actually, a source about conversion of Strings to characters or inputs to Strings would be very helpful as well. It's apparent that this is where a good portion of my understanding is lacking.
public static void main(String args[])
{
int userNum = 0;
int sum = 0;
Scanner s = new Scanner(System.in);
String str3;
System.out.print("Enter positive integers (to exit enter -1):\n ");
//Loop for adding sum with exit -1
while(userNum != -1){
//condition to only calculate positive numbers user entered
if(userNum > 0){
//calculation of all positive numbers user entered
sum += userNum;
str3 = String.valueOf(userNum);}
userNum = s.nextInt();
}
System.out.println("The values of the sum are: " + str3);
System.out.println("The Sum: " + sum);
}
}
I'm hoping for the user input to be printed,
Enter positive integers (to exit enter -1): _ _ ___//with the user
input in the same row.
And...
values from string to read out on same line, not multiple lines.
The variable str needs to be initialized as:
String str3 = "";
and in the loop, each entered number must be concatenated to str.
int userNum = 0;
int sum = 0;
Scanner s = new Scanner(System.in);
String str3 = "";
System.out.print("Enter positive integers (to exit enter -1):\n ");
while (userNum != -1) {
userNum = s.nextInt();
if (userNum > 0) {
sum += userNum;
str3 += " " + userNum;
}
}
System.out.println("The values of the sum are: " + str3);
System.out.println("The Sum: " + sum);

Remove duplicate string elements C++

The problem consists of finding all permutations using k out of n digits. I'm able to find all the permutations, but I'm struggling trying to erase duplicates. I can successfully compare and find the duplicates, but erasing them is what I'm struggling to do. I have a feeling I'm missing something simple but I don't know what it is.
Any help would be greatly appreciated. I've been staring at this for a week.
Here is the code that I've got right now.
void getPermutations(int n, int k)
{
string str = "";
//fill string with numbers <= n
for(int i = 0; i < n; i++)
{
str += to_string(i); //convert numbers to string
}
string tempStr = "";
string outputStr = "";
do {
tempStr = str.substr(0, k);
int compareResult = tempStr.compare(0, k, outputStr, 0, k);
if (compareResult == 0)
{
cout << "| same | ";
outputStr.erase(k,k);
}
outputStr = tempStr;
cout << outputStr << " ";
} while (next_permutation(str.begin(), str.end()));
}
I think what you meant to do was to erase the contents of tempStr, not outputStr.
The call to erase is not exactly right. Its first argument marks the starting position of your erasing, and the second argument tells how many characters to erase. So if you want to erase the whole string, the first argument should be...
You actually don't have to erase anything. After you get it working your way, try to do it without erasing!
Good Luck!

Reduce a string when it has a pair

Shil has a string S , consisting of N lowercase English letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation.
Shil wants to reduce S as much as possible. To do this, he will repeat the above operation as many times as it can be performed. Help Shil out by finding and printing 's non-reducible form!
If the final string is empty, print Empty String; otherwise, print the final non-reducible string.
Sample Input 0
aaabccddd
Sample Output 0
abd
Sample Input 1
baab
Sample Output 1
Empty String
Sample Input 2
aa
Sample Output 2
Empty String
Explanation
Sample Case 0: Shil can perform the following sequence of operations to get the final string:
Thus, we print .
Sample Case 1: Shil can perform the following sequence of operations to get the final string: aaabccddd -> abccddd
abccddd -> abddd
abddd -> abd
Thus we print abd
Sample case 1: baab -> bb
bb -> Empty String.
in my code in the while loop when i assign s[i] to str[i].the value of s[i] is not getting assigned to str[i].the str[i] has a garbage value.
my code :
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
string s;
cin>>s;
int len = s.length();
int len1 = 0;
string str;
for(int i = 0;i < len-1;i++){
if(s[i]!= '*'){
for(int j=i+1;j < len;j++){
if(s[j] != '*'){
if(s[i] == s[j]){
s[i] = s[j] = '*';
}
}
}
}
}
int i = 0;
while(i<len){
if(s[i] != '*'){
str[len1] = s[i];
len1++;
}
i++;
}
if(len1 != 0){
cout<<str;
}
else{
cout<<"Empty String";
}
return 0;
}
#include <iostream>
using namespace std;
int main(){
string s,tempS;
bool condition = false;
cin >> s;
tempS = s;
while(condition==false){
for(int i=1; i<s.size(); i++){
if(s[i]==s[i-1]){
s.erase(s.begin()+i-1, s.begin()+i+1);
}
}
if(tempS == s){
condition = true;
} else{
tempS = s;
}
}
if(s.size()==0){
cout << "Empty String" ;
} else{
cout << s;
}
return 0;
}
the first while loop keeps on modifying the string until and unless it becomes equal to temp (which is equal to the string pre-modification)
It is comparing the adjacent elements if they are equal or not and then deleting them both.
As soon as string becomes equal to temp after modifications, string has reached it's most reduced state !

Specific Characters in Palindrome Program Do not work

Here is my code. The list of characters that do not "work" and continue to say that they are palindromes if wrapped around the cin still say they are correct. The list of characters that don't work are:
single quotes, double quotes, commas, periods, forward slashes, back slashes, dashes, exclamation points, # symbols, # symbols, $ symbols, % symbols, ^ symbols, & symbols, * symbols (asterisk), equals symbols, + symbol
int main()
{
int k = 1;
int i;
int length, halflength;
int yesno = 1;
char string [81];
char end[81] = "END";
while (k = 1)
{
cout << "Please enter a string of characters. " << endl;
cout << "Enter \"END\" in all caps to exit the program." << endl;
cin.getline(string, 81);
if (strcmp(string, "END") == 0)
{
return 0;
}
length = strlen(string);
halflength = length / 2;
for (i = 0; i < halflength; i++)
{
if (string[i] != string[length - i - 1]) // comparing
yesno = 0;
break;
}
if (yesno) {
cout << "You have successfully entered a palindrome." << endl;
}
else
{
cout << "You have not entered a palindrome." << endl;
return main();
}
}
}
I am unsure how to fix this, as a palindrome can not only be a sequence of letters, but a sequence of characters. If there is an easier way to compare the lines, then I would appreciate the help, as I have spent some time being frustrated at this.
your program says,"You have successfully entered a palindrome." for mlaylam!
the problem is not having the break statement in the right place.
the block should be enclosed within braces, otherwise(as you've done), after checking the first character and last, the for loop will break thereby giving wrong result.
if (string[i] != string[length - i - 1]){ // comparing
yesno = 0;
break;
}

Resources