int countChars(string str)
{
int count = 0;
if (str == "")
return count;
else
{
count++;// add a character to the count
return count + countChars(str.substr(1));// function calls itself
}
}
I need to take the above function and call in in the program below and I'm not sure how to initialize it properly. Below is what I tried and it doesn't work. I'm not allowed to use the .length() because otherwise the program would be done.
int main()
{
char find = '\0';
string str;
int count = 0;
int length = int(countChars);
//ask the user for a sentence
cout << "Enter a sentence " << endl;
getline(cin, str);
//ask the user which letter they want the count of
cout << "Which letter would you like to find the number of appearances: " << endl;
cin >> find;
for (int i = 0; i < length; i++)
{
if (str[i] == find)
{
count++;
}
}
cout << "the letter " << find << " appears " << length << " times " << endl;
//waits for user to exit
system("pause");
cin.get();
}
It seems the function should count the number of appearances of a letter in a string. If so then it is declared and defined incorrectly. It has to have at least two parameters an object of type std::string and an object of type char.
Here is shown how such a recursive function can look
#include <iostream>
#include <string>
size_t countChars( const std::string &s, char c )
{
return s.empty() ? 0 : ( s[0] == c ) + countChars( { s, 1 }, c );
}
int main()
{
std::cout << "Enter a sentence ";
std::string s;
std::getline( std::cin, s );
std::cout << "Which letter would you like to find the number of appearances: ";
char c = '\0';
std::cin >> c;
std::cout << "The letter " << c
<< " appears " << countChars( s, c )
<< " times " << std::endl;
return 0;
}
The program output might look like
Enter a sentence My name is Alycia
Which letter would you like to find the number of appearances: a
The letter a appears 2 times
If you mean a function that just calculates the length of a string then it can look like
size_t countChars( const std::string &s )
{
return s.empty() ? 0 : 1 + countChars( { s, 1 } );
}
and shall be called after the statement
getline(cin, str);
Related
I have attempted to remove the occurrences of a user inputted letter after they've chosen a word however, the final output prints out a random string of letters and numbers instead of what I expected. For example, if the user enters the text "Coffee" then proceeds to enter the letter "f", the program should return "Coee" as the final print. However, this is not the case. Could anyone check to see where I've gone wrong? Much obliged.
#include <iostream>
#include <string>
using namespace std;
void removeAllOccurrence(char text[], char letter)
{
int off;
int i;
i = off = 0;
if (text[i] == letter)
{
off++;
}
text[i] = text[i + off];
}
int main() {
string text;
char letter;
string newText;
cout << "Type your text: " << endl;
cin >> text;
cout << "Choose the letters to remove: " << endl;
cin >> letter;
cout << "your new text is: " << removeAllOccurrence << endl;
system("pause");
return 0;
}
This should do the job
#include <algorithm>
#include <string>
#include <iostream>
void remove_char(std::string s, char r) {
s.erase( std::remove( s.begin(), s.end(), r), s.end()) ;
std::cout << s << std::endl;
}
int main()
{
std::string test = "coffee";
char r = 'f';
remove_char(test, r);
return 0;
}
If u want to do this by hand try this:
std::string removeAllOccurrence(string text, char letter)
{
int off;
int i;
i = off = 0;
string out = "";
for (i = 0; i < text.size(); i++)
{
if (text[i] != letter)
{
out += text[i];
}
}
return out;
}
int main(void)
{
string text;
char letter;
string newText;
cout << "Type your text: " << endl;
cin >> text;
cout << "Choose the letters to remove: " << endl;
cin >> letter;
cout << "your new text is: " + removeAllOccurrence(text, letter) << endl;
system("pause");
return 0;
}
As you can see your main function was kinda right. You just need to pass some arguments into the function. Additonally you missed a loop in your remove function. If you use string in your main, why don't use string in yur function? You can just use string there, too
Kind Regards
I have to make a simple letter guessing game. So far I've finished almost everything but I'm not sure about what to do when it comes to one task.
So before the game begins it asks the user to input two things:
Enter the amount of different characters: (if 4 is entered for example, the letters chosen would be from A to the 4th letter, A-D only)
and
Enter the pattern length:
The pattern length input is working fine, but I'm having a tough time figuring out how to modify the generate code function to add the amount of different characters.
Any tips?
#include <iostream>
#include <random>
#include <string>
using namespace std;
size_t len;
string str;
void generate_code()
{
str.string::reserve(len);
random_device rd;
mt19937 gen{rd()};
uniform_int_distribution<char> dis{'A', 'Z'};
for (size_t i = 0; i < len; i++)
{
str += dis(gen);
}
}
void guess_checker()
{
string guess{};
size_t trial_count = 0, match_count = 0;
do
{
cout << "Enter your guess: " << endl;
cin >> guess;
if (guess.size() != len)
{
cout << "error: invalid guess" << endl;
}
else
{
match_count = 0;
for (size_t i = 0; i < len; i++)
{
if (guess[i] == str[i])
++match_count;
}
cout << "You guessed " << match_count << " character"
<< (match_count == 1 ? "" : "s") << " correctly." << endl;
}
++trial_count;
}
while (match_count != len);
cout << "You guessed the pattern in " << trial_count << " guess"
<< (trial_count == 1 ? "" : "es") << "." << endl;
}
int main()
{
int amount;
cout << "Enter the amount of different characters: ";
cin >> amount;
cout << "Enter the pattern length: ";
cin >> len;
generate_code();
guess_checker();
return 0;
}
Simply change your generator line to:
uniform_int_distribution<char> dis{'A', 'A' + amount - 1};
I would also recommend adding some validation beforehand, such as:
if (amount < 1 || amount > 26) {
cout << "Bad amount" << endl;
// exit or something
}
This is my first time asking a question on here, so be gentle lol. I wrote up some code for an assignment designed to take information from a (library.txt datatbase) file, store it in arrays, then access/search those arrays by title/author then output that information for the user based on what the user enters.
The issue I am having is, whenever the user enters in a search term longer than one word, the output of "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All: " is repeated several times before closing.
I am just looking to make this worthy of my professor lol. Please help me.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
struct Book
{
string title;
string author;
};
int loadData(string pathname);
char switchoutput();
void showAll(int count);
int showBooksByAuthor(int count, string name);
int showBooksByTitle(int count, string title);
int FindAuthor(int count, string userinput);
int FindTitle(int count, string userinput);
void ConvertStringToLowerCase(const string orig, string& lwr); //I found this program useful to convert any given string to lowercase, regardless of user input
const int ARRAY_SIZE = 1000;
Book books[ARRAY_SIZE];
int main()
{
string pathname;
string name;
string booktitle;
int count = 0;
int counta = 0;
int countt = 0;
char input = 0;
cout << "Welcome to Jacob's Library Database." << endl;
cout << "Please enter the name of the backup file: " ;
cin >> pathname;
count = loadData(pathname);
cout << count << " records found in the database." << endl;
while (toupper(input != 'Q'))
{
input = switchoutput(); // function call for switchoutput function
switch (input)
{
case 'A':
cout << "Author's Name: ";
cin >> name;
counta = showBooksByAuthor(count, name);
cout << counta << " records found." << endl;
break;
case 'T':
cout << "Book Title: ";
cin >> booktitle;
countt = showBooksByTitle(count, booktitle);
cout << countt << " records found." << endl;
break;
case 'S':
showAll(count);
break;
case 'Q':
break;
}
}
//Pause and exit
cout << endl << "Press 'ENTER' to quit";
getchar();
getchar();
return 0;
}
int loadData(string pathname) //loading data into the array of structs
{
ifstream inFile;
inFile.open(pathname);
if (!inFile) {
cout << "Error, could not read into file. Please re-compile." << endl;
system("PAUSE");
exit(1); //if not in file, exit;
}
int i = 0;
while (!inFile.eof()) {
getline(inFile, books[i].title);
getline(inFile, books[i].author);
i++;
}
return i;
}
char switchoutput() //seperate output function to get my characteroutput constantly resetting and returning the uppercase version for my switch
{
char input;
cout << "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All: ";
cin >> input;
return toupper(input);
}
int showBooksByAuthor(int count, string name)
{
int authorcount = 0;
authorcount = FindAuthor(count, name);
return authorcount;
}
int showBooksByTitle(int count, string title)
{
int titlecount = 0;
titlecount = FindTitle(count, title);
return titlecount;
}
void showAll(int count)
{
for (int i = 0; i < count; i++)
{
cout << books[i].title << " (" << books[i].author << ")" << endl;
}
}
int FindAuthor(int count, string userinput)
{
int authorcount = 0;
string stringlower, arraylower;
int num;
// called upon function to lowercase any of the user inputs
ConvertStringToLowerCase(userinput, stringlower);
for (int i = 0; i < count; ++i) //this function's count determines at which locations to output the author and names (an argument from books by author)
{
// called upon function to lowercase any of the stored authors'
ConvertStringToLowerCase(books[i].author, arraylower);
num = arraylower.find(stringlower); // searches string for userinput (in the lowered array) and stores its value
if (num > -1) // you can never get a -1 input value from an array, thus this loop continues until execution
{
cout << books[i].title << " (" << books[i].author << ")" << endl; //cout book title and book author
authorcount++; //count
}
}
return authorcount;
}
int FindTitle(int count, string userinput) //same as previous but for titles
{
int titlecount = 0;
string stringlower, arraylower;
int num;
ConvertStringToLowerCase(userinput, stringlower);
for (int i = 0; i < count; ++i)
{
ConvertStringToLowerCase(books[i].title, arraylower);
num = arraylower.find(stringlower);
if (num > -1)
{
cout << books[i].title << " (" << books[i].author << ")" << endl;
titlecount++; //count
}
}
return titlecount;
}
void ConvertStringToLowerCase(const string orig, string& lwr) // I found this from another classmate during tutoring, I thought to be useful.
{
lwr = orig;
for (int j = 0; j < orig.length(); ++j) //when called upon in my find functions, it takes the string and convers the string into an array of lowercase letters
{
lwr[j] = tolower(orig.at(j));
}
}
searchingWrite a function conseclets which will receive one string as parameter. The function will determine all cases in which two or more consecutive letters in the string are identical.
For example, if "Barrymoore" is sent to the function, it will say that there are consecutive letters r and o in the string. But if "Bush" is sent to the function, it will say there are no two consecutive letters which are the same.
Here is my code the problem with it is when I put in a letter to find it finds it but not consecutively
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char searching='\0';
string name=" ";
int counter =0;
cout<<"Enter a name : "<<endl;
getline(cin, name);
cout<<"Which letter would you like to count the number of times it appears: "<<endl;
cin>>name;
for(int i=0; i<name.length();i++){
if(sentence[i]==searching){
counter++;
}
}
cout<<"The letter " << searching << " appears "<< counter << " times ";
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main(int argc, char *argv[]) {
char a[30];
int i,c=0;
printf("enter a string\n");
gets(a);
for(i=0;i<strlen(a);i++)
{
if(a[i]==a[i+1])
{
printf("%c is consecutive\n",a[i]);
c++;
}
}
if(c==0)
{
printf("No consecutive letters");
}
return 0;
}
// Check this. This is proper code for your problem.
Here is an implementation making use of the standard algorithm library. I've called "runs" the sequences of identical consecutive letters. The algorithm is not necessarily optimal, but it's simple and that matters too.
void conseclets(std::string const &str) {
// Keep the end of the string, and point i to the first run's beginning
auto e = end(str), i = std::adjacent_find(begin(str), e);
if(i == e)
std::cout << "No repetition.\n";
else do {
// Locate the end of the run (that is, the first different letter)
auto next = std::find_if(i, e, [&i](auto const &c){ return c != *i; });
// Print out the match
std::cout << "Letter " << *i << " is repeated "
<< std::distance(i, next) << " times.\n";
// Skip to the next run's beginning
i = std::adjacent_find(next, e);
// Do so until we reached the end of the string
} while(i != e);
}
Live on Coliru
though there are several ways to do it, just modifying yours optimally to achieve whats required here :
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
char searching = '\0';
string name = " ";
int counter = 0;
cout << "Enter a name : " << endl;
getline(cin, name);
cout << "Which letter would you like to count the number of times it appears: " << endl;
cin >> searching;
for (int i = 0; i < name.length(); i++) {
if (name[i] == searching) {
counter++;
}
}
cout << "The letter " << searching << " appears " << counter << " times ";
return 0;
}
#include <iostream>
#include <iterator>
using namespace std;
template<typename I, typename O> O repeats(I b, I e, O result){
while(b!=e){
bool once = true;
I p = b;
while(++b!=e && *p==*b){
if(once){
*result++ = *p;
once = false;
}
}
}
return result;
}
int main() {
string name = "Barrymoore";
string res;
repeats(begin(name), end(name), back_inserter(res));
cout << "There are " << res.size() << " consecutive letters :" << res << endl;
return 0;
}
I need to make some functions but i don't know how.
join two strings, input positions and output the characters from the position in the string
Example: s1=first, s2=second; s1+s2=firstsecond, pos=3,7,10, output=ren
this is my code for one postion, but i don't know how to make for several position, main problem is how to limit input of position:
s=s1+s2;
cin>>pos;
cout<<s[pos-1];
define vowel in string and replace that vowel with string
Example: s=firstsecondthird, vowel=i, str=EXA, output=fEXArstsecondthEXArd
This is what i know, i don't know how to make the replacing vowel with string(str)
cin>>vowel;
if(check is defined character vowel)
{
cin>>str;
.
.
.
}
Thank you
Catch! :)
#include <iostream>
#include <string>
#include <cstring>
int main()
{
std::cout << "Enter first string: ";
std::string s1;
std::cin >> s1;
std::cout << "Enter second string: ";
std::string s2;
std::cin >> s2;
s1 += s2;
std::cout << "The joined string is " << s1 << std::endl;
std::cout << "Enter several positions in the joined string (0-stop): ";
std::string s3;
std::string::size_type pos;
while ( std::cin >> pos && pos != 0 )
{
if ( --pos < s1.size() ) s3 += s1[pos];
}
std::cout << "You have selected the following letters " << s3 << std::endl;
const char *vowels = "aeiou";
char c;
do
{
c = '\0';
std::cout << "Enter a vowel: ";
} while ( std::cin >> c && !std::strchr( vowels, c ) );
if ( c != '\0' )
{
for ( auto pos = s1.find( c, 0 );
pos != std::string::npos;
pos = s1.find( c, pos ) )
{
const char *t = "EXA";
const size_t n = 3;
s1.replace( pos, 1, t );
pos += n;
}
std::cout << "Now the joined string looks like " << s1 << std::endl;
}
return 0;
}
If to enter
first
second
3 7 10 0
i
then the program output will be
Enter first string: first
Enter second string: second
The joined string is firstsecond
Enter several positions in the joined string (0-stop): 3 7 10 0
You have selected the following letters ren
Enter a vowel: i
Now the joined string looks like fEXArstsecond
You can use it as a template for your great program.:)