I am currently in my last year of a BS in Information Systems with a major in programming. I took and passed C++ programming 1. I am now in C++ programming 2 and am having trouble with recursive functions. We have a homework assignment, where we are suppose to write a program that will count the number of vowels in a string that is entered by the user.
I have a program similar to this from my C++ programming 1 class that works using a for loop and if-then statements. I had assumed that it would be easy to convert this working program to use a recursive function, I was wrong.
I have the code (not looking for someone to do it for me) and I think i have it setup right. Just am not sure where to put the call to the function within the function.
Can somebody point me in the right direction?`
This is my first time asking a question. If i attached my code wrong, please let me know.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int vowelCount(string, int, int&);
int mail()
{
string input;
int len;
//int x;
//int y;
int count;
count = 0;
cout << "Enter a string of characters with no spaces: ";
cin >> input;
len = input.length();
vowelCount(input, len, count);
cout << "There were " << count << " vowels." << endl;
system("pause");
return 0;
}
int vowelCount(string input, int len, int& count)
{
int y;
int x;
y = input.at(len);
if (len == 1)
{
count = count + 1;
return count;
}
else
{
y = input.at(len);
if ((y == 'a') || (y == 'e') || (y == 'i') || (y == 'o') || (y == 'u') || (y == 'A') || (y == 'E') || (y == 'I') || (y == 'O') || (y == 'U'))
{
count = count + 1;
len = len - 1;
}
else
{
len = len - 1;
vowelCount(string input, int len, int& count);
return count;
}
}
}
return 0;
}
For a general understanding, I recommend the answers to this question.
First of all, this code doesn't run: it has syntax errors. You shouldn't be asking for logic help until you have a program that at least runs. You cannot call a function with the entire signature. FOr instance, the final block should be a simple
return vowelCount(input, len-1)
You're returning the count as both the function's value and a parameter. Drop the parameter.
Now, for understanding the recursion ... take this in a couple of steps:
If the string is empty, return 0.
Otherwise, check the current letter:
2T if it's a vowel, return 1 + {count on rest of string}
2F else, return {count on rest of string}
Your two recursive calls are in the braces. Can you take it from here?
I would write the function the following way
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
std::string::size_type vowelCount( const std::string &input, std::string::size_type pos = 0 )
{
const char *vowels = "AEIOU";
return pos >= input.size()
? 0
: ( std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr )
+ vowelCount( input, pos + 1 );
}
int main()
{
std::string s;
std::cin >> s;
std::cout << "There were " << vowelCount( s ) << " vowels." << std::endl;
return 0;
}
If for example to enter
AaBbCcDdEe
then the output will be
There were 4 vowels.
I suppose that the string does not contain embedded zero characters.:)
Otherwise you should substitute the condition
( std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr )
for
( input[pos] != '\0' && std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr )
As for your function then if to write it syntactically valid it does not make sense due to for example this statement
int vowelCount(string input, int len, int& count)
{
int y;
int x;
y = input.at(len);
^^^^^^^^^^^^^^^^^^
because according to the C++ Standard member function at
5 Throws: out_of_range if pos >= size().
Related
The problem is that it always outputs 0 (false) as a result. Probably the problem is in the isPalindrome function, but I cannot figure where exactly. Would be grateful if someone helped.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
bool isPalindrome(string word)
{
bool result;
for (int i = 0; i <= word.length() - 1; i++)
{
if (word.at(i) == word.length() - 1)
{
result = true;
}
else
{
result = false;
}
return result;
}
}
int main()
{
string word1;
int count;
cout << "How many words do you want to check whether they are palindromes: " << flush;
cin >> count;
for (int i = 0; i < count; i++)
{
cout << "Please enter a word: " << flush;
cin >> word1;
cout << "The word you entered: " << isPalindrome(word1);
}
}
Try this one:
bool isPalindrome(string word)
{
bool result = true;
for (int i = 0; i < word.length() / 2; i++) //it is enough to iterate only the half of the word (since we take both from the front and from the back each time)
{
if (word[i] != word[word.length() - 1 - i]) //we compare left-most with right-most character (each time shifting index by 1 towards the center)
{
result = false;
break;
}
}
return result;
}
In this statement
if (word.at(i) == word.length() - 1)
the right side expression of the comparison operator is never changed and have the type std::string::size_type instead of the type char. You mean
if (word.at(i) == word.at( word.length() - 1 - i ))
However there is no sense to use the member function at. You could us the subscript operator. For example
if ( word[i] == word[word.length() - 1 - i ] )
And the loop should have word.length() / 2 iterations.
Also within the loop you are overwriting the variable result. So you are always returning the last value of the variable. It can be equal to true though a string is not a palindrome.
Also the parameter should be a referenced type. Otherwise a redundant copy of the passed argument is created.
The function can be defined the following way
bool isPalindrome( const std::string &word )
{
std::string::size_type i = 0;
std::string::size_type n = word.length();
while ( i < n / 2 && word[i] == word[n - i - 1] ) i++;
return i == n / 2;
}
Another approach is the following
bool isPalindrome( const std::string &word )
{
return word == std::string( word.rbegin(), word.rend() );
}
Though this approach requires to create a reverse copy of the original string.
The simplest way is to use the standard algorithm std::equal. Here is a demonstrative program
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
bool isPalindrome( const std::string &word )
{
return std::equal( std::begin( word ),
std::next( std::begin( word ), word.size() / 2 ),
std::rbegin( word ) );
}
int main()
{
std::cout << isPalindrome( "123454321" ) << '\n';
return 0;
}
I hope this one helps you also (corrected also warnings):
bool isPalindrome(string word)
{
bool result = false;
int lengthWord = (int)word.length();
for (int i = 0; i <= (lengthWord / 2); ++i)
{
if (word.at(i) == word.at(lengthWord - i -1))
{
result = true;
continue;
}
result = false;
}
return result;
}
Two possible problems.
You appear to be comparing a character to a number
if (word.at(i) == word.length() - 1)
shouldn't this be
if (word.at(i) == word.at(word.length() - i)) ?
There are 3 returns within the if statement, so no matter what the outcome it's only going to compare one character before returning to the calling function.
As a point of technique, repeated calls to .length inside the loop, which always returns the same value, wastes time and makes the code more difficult to understand.
You need to return as soon as you find a mismatch. If you are looking for a palindrome you only need to compare the first half of the word with the second half in reverse order. Something like
bool isPalindrome(string word)
{
for (int i = 0, j= word.length() - 1; i<j; i++, j--)
// i starts at the beginning of the string, j at the end.
// Once the i >= j you have reached the middle and are done.
// They step in opposite directions
{
if (word[i] != word[j])
{
return false;
}
}
return true;
}
The loop in the function isPalindrome will only execute once, because the return statement is unconditionally executed in the first iteration of the loop. I am sure that this is not intended.
To determine whether a string is a palindrome, the loop must be executed several times. Only after the last character has been evaluated (in the last iteration of the loop) will it be time to use the return statement, unless you determine beforehand that the string is not a palindrome.
Also, in the function isPalindrome, the following expression is nonsense, as you are comparing the ASCII Code of a letter with the length of the string:
word.at(i) == word.length() - 1
Therefore, I suggest the following code for the function:
bool isPalindrome(string word)
{
for (int i = 0; i < word.length() / 2; i++)
{
if (word.at(i) != word.at( word.length() - i - 1) ) return false;
}
return true;
}
As discussed in the comments under your question. You made some mistakes in the code.
Your function should more or less look like this:
bool isPalindrome(string word) {
bool result = true;
for (int i = 0; i <= word.length() - 1; i++)
{
if (word.at(i) != word.at(word.length() - 1 -i))
{
return false;
}
}
return result;
}
I am trying to convert input text/numbers (string), which will include any characters, but I want to separate the numbers from the characters and store them into an integer array, once it is converted from a string.
I believe the problem is where the string is converting to an integer by use of stoi(), but I cannot seem to spot the problem.
Currently, the code accepts any input and turns it into a string, the string is then checked character by character, and all the numbers without separation with comma or space is added together, once a comma or space, or any other character separates the number, the number as a whole is added to the array, and then continues to check the string for more numbers.
Any ideas?
Input Example1: 12, 13, 15
Input Example2: 12 13 15
Input Example3: 12ab13cd15ef
Result in integer array: 0[12] 1[13] 2[15]
These numbers will be used in the specific order, by using the numbers within the array.
#include<iostream>
#include<string>
#include <sstream>
using namespace std;
int main()
{
string datainput, str1, str3;
cin >> datainput;
int n = 0, raycount = 0, c;
int myray[10];
while (datainput[n])
{
if (datainput[n] == ('0') || datainput[n] == ('1') || datainput[n] == ('2') || datainput[n] == ('3') || datainput[n] == ('4') ||
datainput[n] == ('5') || datainput[n] == ('6') || datainput[n] == ('7') || datainput[n] == ('8') || datainput[n] == ('9'))
{
str1 = datainput[n];
str3 += str1;
}
else
{
c= stoi(str3);
c >> myray[raycount];
raycount++;
}
n++;
}
cout << myray[0] << endl;
cout << myray[1] << endl;
cout << myray[2] << endl;
cout << myray[3] << endl;
system("pause");
return 0;
}
I see quite a few issues with your code.
Prior to C++11, while (datainput[n]) has undefined behavior once n reaches the end of the string.
The way you are checking for numeric digits can be greatly simplified using std::isdigit(), or even just a simple range check using the >= and <= operators.
You are not correctly accounting for numbers that are separated by other characters, or when the last number in the string is at the very end of the string.
The statement c >> myray[raycount]; needs to be changed to myray[raycount] = c; instead. And you are not breaking your loop if raycount reaches the max capacity of myray[].
You are not resetting str3 back to an blank string after converting it with std::stoi(). You just keep appending new digits to the end of previous digits with no break in between numbers.
With that said, try something more like this instead:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string datainput, str3;
cin >> datainput;
int myray[10];
int raycount = 0;
bool gettingDigits = false;
for (int n = 0; n < datainput.size(); ++n)
{
char ch = datainput[n];
//if (isdigit(ch))
if (ch >= '0' && ch <= '9')
{
if (!gettingDigits)
{
str3 = "";
gettingDigits = true;
}
str3 += ch;
}
else
{
if (gettingDigits)
{
myray[raycount] = stoi(str3);
raycount++;
str3 = "";
gettingDigits = false;
if (raycount == 10) break;
}
}
}
if (gettingDigits && (raycount < 10))
{
myray[raycount] = stoi(str3);
raycount++;
}
for (int n = 0; n < raycount; ++n)
cout << myray[n] << endl;
system("pause");
return 0;
}
Live Demo
Alternatively:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string datainput, str3;
cin >> datainput;
int myray[10];
int raycount = 0;
string::size_type start = datainput.find_first_of("0123456789");
string::size_type end;
while (start != string::npos)
{
end = datainput.find_first_not_of("0123456789", start+1);
if (end == string::npos)
{
str3 = datainput.substr(start);
myray[raycount] = stoi(str3);
raycount++;
break;
}
str3 = datainput.substr(start, end-start);
myray[raycount] = stoi(str3);
raycount++;
if (raycount == 10) break;
start = datainput.find_first_of("0123456789", end+1);
}
for (int n = 0; n < raycount; ++n)
cout << myray[n] << endl;
system("pause");
return 0;
}
Live Demo
So, you want to segregate numbers and characters into different arrays.
In if block, you are checking for characters, so, I suspect stoi() wouldn't work.
Better typecast it to an integer.
int temp[10];
if (datainput[n] == ('0') || ...) {
temp[n] = int(datainput[n]);
}
This way your temp array would contain the numbers.
I was training on solving algorithms, I wrote a code but it won't compile
in (if) I can not check s[i]=='S' .
I'm trying to if s[i] is S character or not but I don't know where my problem is.
If I can't use this syntax, what could be a solution?
#include<iostream>
#include<string>
using namespace std;
int main()
{
double v_w=25,v_s=25,d_w=25,d_s=25;
int n;
cin>>n;
string s[]={"WSSS"};
int i ;
for (i=0; i<n; i++)
{
if( s[i] == "W" )
{
v_s += 50;
d_w = d_w + (v_w/2);
d_s = d_s + (v_s/2);
cout<<"1 \n";
}
if(s[i]=='W')
{
v_w +=50;
d_w = d_w + (v_w/2);
d_s = d_s + (v_s/2);
cout<<"2 \n";
}
return 0;
}
cout<< d_w<<endl<<d_s;
}
string s[]={"WSSS"}; means an array of strings which the first one is "WSSS".
What you need is:
std::string s="WSSS";
string s[] = {"Hello"} is an array of strings (well, of one string).
If you iterate over it, or index into it s[0] is "Hello".
Whereas
string s{"Hello"} is one string, which is made up of characters.
If you iterate over it, or index into it s[0], you will get 'H'.
To pre-empt all the other things that are going to go wrong when the string versus character problem is sorted, lets move the return 0; from the middle of the for loop.
Then let's think about what happens if the number n entered is larger than the length of the string:
int n;
cin>>n; //<- no reason to assume this will be s.length (0 or less) or even positive
string s{"WSSS"}; //one string is probably enough
int i ;
for(i=0;i<n;i++)
{
if( s[i] == 'W' ) //ARGGGGGGG may have gone beyond the end of s
{
In fact, let's just drop that for now and come back to it later. And let's use a range based for loop...
#include<iostream>
#include<string>
using namespace std;
int main()
{
double v_w = 25, v_s = 25, d_w = 25, d_s = 25;
string s{ "WSSS" };
for (auto && c : s)
{
if (c == 'W')
{
v_w += 50;
d_w = d_w + (v_w / 2);
d_s = d_s + (v_s / 2);
cout << "2 \n";
}
}
cout << d_w << '\n' << d_s << '\n'; //<- removed endl just because...
return 0;
}
s is an array of strings in this case it has only element:
string s[] = {"WSSS"};
so writing s[2]; // is Undefined behavior
your code will produce a UB if the user enters n greater than the number of elements in s:
n = 4;
for(i = 0; i < n; i++) // s[3] will be used which causes UB
{
if( s[i] == 'W' ) // s[i] is a string not just a single char
{
}
}
also as long as s is an array of strings then to check its elements check them as strings not just single chars:
if( s[i] == "W" ) // not if( s[i] == 'W' )
I think you wanted a single string:
string s = {"WSSS"};
because maybe you are accustomed to add the subscript operator to character strings:
char s[] = {"WSSS"};
if so then the condition above is correct:
if( s[i] == 'W' )
For an assignment, I am working on creating a word shifter in C++. I have little to no experience with C++ so it has been very difficult. I think I am really close but just missing some syntax that is part of C++. Any help would be appreciated greatly.
string s = phrase;
int length = s.length();
//find length of input to create a new string
string new_phrase[length];
//create a new string that will be filled by my for loop
for (int i=0; i<length; i++)
//for loop to go through and change the letter from the original to the new and then put into a string
{
int letter = int(s[i]);
int new_phrase[i] = letter + shift;
//this is where I am coming up with an error saying that new_phrase is not initialized
if (new_phrase[i] > 122)
//make sure that it goes back to a if shifting past z
{
new_phrase[i] = new_phrase[i] - 26;
}
}
cout << new_phrase<< endl;
Considering your syntax,I wrote an example for you.Besides,it is conventional
to write comment before it's relevant code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//test value;
int shift = 3;
string s = "hello string";
//find length of input to create a new string
int length = s.length();
//create a new string.it's length is same as 's' and initialized with ' ';
string new_phrase(length, ' ');
for (int i=0; i<length; i++)
{
//no need to cast explicitly.It will be done implicitly.
int letter = s[i];
//It's assignment, not declaration
new_phrase[i] = letter + shift;
//'z' is equal to 126.but it's more readable
if (new_phrase[i] > 'z')
{
new_phrase[i] = new_phrase[i] - ('z' - 'a' + 1);
}
}
cout << new_phrase<< endl;
}
This should work.
// must be unsigned char for overflow checking to work.
char Shifter(unsigned char letter)
{
letter = letter + shift;
if (letter > 'z')
letter = letter - 26;
return letter;
}
// :
// :
string new_phrase = phrase; // mainly just allocating a string the same size.
// Step throught each char in phrase, preform Shifter on the char, then
// store the result in new_phrase.
std::transform(phrase.begin(), phrase.end(), new_phrase.begin(), Shifter);
cout << new_phrase<< endl;
UPDATE: made letter unsigned, so the overflow check works.
Try and investigate this code
#include <iostream>
#include <string>
#include <cctype>
void ShiftRight( std::string &s, std::string::size_type n )
{
if ( n >= 'Z' - 'A' + 1 ) return;
for ( char &c : s )
{
bool lower_case = std::islower( c );
c = std::toupper( c );
c = ( c + n -'A' ) % ('Z' -'A' + 1 ) + 'A';
if ( lower_case ) c = std::tolower( c );
}
}
int main()
{
std::string s( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" );
std::cout << s << std::endl << std::endl;
for ( std::string::size_type i = 1; i <= 'Z' -'A' + 1; i++ )
{
std::str std::string s( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" );
ShiftRight( s, i );
std::cout << s << std::endl;
}
return 0;
}
The output is
ABCDEFGHIJKLMNOPQRSTUVWXYZ
BCDEFGHIJKLMNOPQRSTUVWXYZA
CDEFGHIJKLMNOPQRSTUVWXYZAB
DEFGHIJKLMNOPQRSTUVWXYZABC
EFGHIJKLMNOPQRSTUVWXYZABCD
FGHIJKLMNOPQRSTUVWXYZABCDE
GHIJKLMNOPQRSTUVWXYZABCDEF
HIJKLMNOPQRSTUVWXYZABCDEFG
IJKLMNOPQRSTUVWXYZABCDEFGH
JKLMNOPQRSTUVWXYZABCDEFGHI
KLMNOPQRSTUVWXYZABCDEFGHIJ
LMNOPQRSTUVWXYZABCDEFGHIJK
MNOPQRSTUVWXYZABCDEFGHIJKL
NOPQRSTUVWXYZABCDEFGHIJKLM
OPQRSTUVWXYZABCDEFGHIJKLMN
PQRSTUVWXYZABCDEFGHIJKLMNO
QRSTUVWXYZABCDEFGHIJKLMNOP
RSTUVWXYZABCDEFGHIJKLMNOPQ
STUVWXYZABCDEFGHIJKLMNOPQR
TUVWXYZABCDEFGHIJKLMNOPQRS
UVWXYZABCDEFGHIJKLMNOPQRST
VWXYZABCDEFGHIJKLMNOPQRSTU
WXYZABCDEFGHIJKLMNOPQRSTUV
XYZABCDEFGHIJKLMNOPQRSTUVW
YZABCDEFGHIJKLMNOPQRSTUVWX
ZABCDEFGHIJKLMNOPQRSTUVWXY
ABCDEFGHIJKLMNOPQRSTUVWXYZ
As for your code then it of course is wrong. You have not to define an array of strings. And do not use magic numbers as for example 122.
Also you may include in my code a check that a next symbol is an alpha symbol.
I saw this problem online, and I was trying to solve it in C++. I have the following algorithm:
char permutations( const char* word ){
int size = strlen( word );
if( size <= 1 ){
return word;
}
else{
string output = word[ 0 ];
for( int i = 0; i < size; i++ ){
output += permutations( word );
cout << output << endl;
output = word[ i ];
}
}
return "";
}
For example, if I have abc as my input, I want to display abc, acb, bac, bca, cab, cba.
So, what I'm trying to do is
'abc' => 'a' + 'bc' => 'a' + 'b' + 'c'
=> 'a' + 'c' + 'b'
so I need o pass a word less char every function call.
Could someone please help how to do it?
I suggest doing it using the algorithm header library in C++, much easier; and as a function can be written like this:
void anagram(string input){
sort(input.begin(), input.end());
do
cout << input << endl;
while(next_permutation(input.begin(), input.end()));
}
However since you want it without the STL, you can do it like so:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap (char *x, char *y)
{
char ch = *x;
*x = *y;
*y = ch;
};
void permutate_(char* str, size_t index )
{
size_t i = 0;
size_t slen = strlen(str);
char lastChar = 0;
if (index == slen )
{
puts(str);
return;
}
for (i = index; i < slen; i++ )
{
if (lastChar == str[i])
continue;
else
lastChar = str[i];
swap(str+index, str+i);
permutate_(str, index + 1);
swap(str+index, str+i);
}
}
// pretty lame, but effective, comparitor for determining winner
static int cmpch(const void * a, const void * b)
{
return ( *(char*)a - *(char*)b );
}
// loader for real permutor
void permutate(char* str)
{
qsort(str, strlen(str), sizeof(str[0]), cmpch);
permutate_(str, 0);
}
Which you can call by sending it a sorted array of characters,
permutate("Hello World");
The non-STL approach was gotten from here.
The STL is wonderful:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void permutations(const char *word) {
string s = word;
sort(s.begin(), s.end());
cout << s << endl;
while(next_permutation(s.begin(), s.end()))
cout << s << endl;
}
int main() {
permutations("abc");
return 0;
}
Now, next_permutation can be implemented quite simply. From the end of the string, iterate backwards until you find an element x which is less than the next element. Swap x with the next value larger than x in the remainder of the string, and reverse the elements coming afterwards. So, abcd becomes abdc since c < d; cdba becomes dabc since c < d and we flip the last three letters of dcba; bdca becomes cabd because b < d and we swap b for c.