I want to remove occurrences of a given letter - c++

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

Related

Find a word in a sentence c++

This code should say if a word is present in a sentence or not. When I insert the sentence and the word where I declare the strings(for exemple: string s = "the cat is on the table" string p = "table" the program says that the word is in the sentence) the code works but, with the getline, the for cycle never begin and it always says that the word isn't in the sentence.
Please help I dont know what to do
#include <iostream>
#include <string>
using namespace std;
int main () {
string s;
string p;
string word;
bool found = false;
int sl = s.length();
int beg = 0;
int pl = p.length();
cout << "sentence: ";
getline(cin, s);
cout << "word: ";
getline(cin, p);
for(int a = 0; a<sl; a++)
{
if(s[a]== ' ')
{
word = s.substr(beg, a-beg);
if (word== p)
{
found = true;
break;
}
beg = a+1;
}
}
if (found== true)
{
cout <<"word " << p << " is in a sentence " << s;
}
else
{
word = s.substr(beg);
if (word== p)
{
found = true;
}
if(found == true)
{
cout <<"the word " << p << " is in the sentence " << s;
}
else
{
cout <<"the word " << p << " isn't in the sentence " << s;
}
}
}
after taking the input strings then use length() to find the length, otherwise you are not taking the actual size of the strings.
getline(cin, s);
getline(cin, p);
int sl = s.length();
int pl = p.length();
For splitting the words after taking the input string by getline() you can use stringstream which is a builtin c++ function, like :
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string arr;
getline(cin, arr);
stringstream ss(arr);
string word;
while(ss >> word){
// your desired strings are in `word` one by one
cout << word << "\n";
}
}
Another thing is that you can declare the strings like string s, p, word;

c++ problem with reverse and count string

I'm just learning c++. I have a problem with my program. I have to write a program which reverse string and count amount word in the string. My program doesn't return amount words and reverse only last word in string. I totally don't know how to correct it. :D
#include <iostream>
using namespace std;
void reverseString(string str)
{
for (int i=str.length()-1; i>=0; i--)
{
cout << str[i];
}
}
void countString(string strg)
{
int word = 1;
for(int j = 0; strg[j] != '\0'; j++)
{
if (strg[j] == ' ')
{
word++;
}
}
}
int main(void)
{
string inputString;
cout << "Give a string: ";
cin >> inputString;
cout << "Reverse string: ";
reverseString(inputString);
cout << "\nCounts words in a string: ";
countString(inputString);
return 0;
}
If you want to read multiple words then you must use getline as >> reads only a single word.
string inputString;
cout << "Give a string: ";
getline(cin, inputString);
To return something from a function you must 1) specify the return type and 2) use a return statement to return a value and 3) do something with that return value in the calling function
Step 1
int countString(string strg) // here we say countString returns an integer
{
...
}
Step 2
int countString(string strg)
{
...
return words; // here we say the value we want to return
}
Step 3
// here we output the value returned from the function
cout << "\nCounts words in a string: " << countString(inputString) << "\n";
Knowing how to write functions that return values is absolutely fundamental C++. You should practise this. See if you can do the same with your reverseString function, instead of printing a string make it return a string.
There are some mistake in your code.In countString() function you return nothing.So it does not print anything.If you take input as a string include a space character,please use getline(cin, inputString).Here the code for you:
#include <iostream>
using namespace std;
void reverseString(string str)
{
for (int i=str.length()-1; i>=0; i--)
{
cout << str[i];
}
}
int countString(string strg)
{
int word = 0;
for(int j = 0; strg[j] != '\0'; j++)
{
word++;
}
return word;
}
int main(void)
{
string inputString;
cout << "Give a string: ";
getline(cin, inputString);
cout << "Reverse string: ";
reverseString(inputString);
cout << "\nCounts words in a string: ";
cout<<countString(inputString)<<endl;
return 0;
}

Read new line character in fstream C++

How do I read the new line character? I am trying to do a character count, but the new line gets in the way. I tried doing if (text[i] == ' ' && text[i] == '\n') but that didn't work. Here is my repl.it session.
I am trying to read this from file.txt:
i like cats
dogs are also cool
so are orangutans
This is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream input;
input.open("file.txt");
int numOfWords = 0;
while (true)
{
string text;
getline(input, text);
for(int i = 0; i < text.length(); i++)
{
if (text[i] == ' ')
{
numOfWords++;
}
}
if (input.fail())
{
break;
}
}
cout << "Number of words: " << numOfWords+1 << endl;
input.close();
}
Your question is asking how to count characters, but your code is counting words instead. std::getline() swallows line breaks. You don't need to worry about them if you want to count words. In fact, you can use operator>> to greatly simplify your counting in that case, eg:
int main()
{
ifstream input("file.txt");
int numOfWords = 0;
string word;
while (input >> word)
++numOfWords;
cout << "Number of words: " << numOfWords << endl;
return 0;
}
If you really want to count characters instead of words, use std::ifstream::get() to read the file 1 character at a time, eg:
int main()
{
ifstream input("file.txt");
int numOfChars = 0;
int numOfWords = 0;
bool isInSpace = true;
char ch;
while (input.get(ch))
{
++numOfChars;
if (std::isspace(ch, input.getloc())) {
isInSpace = true;
}
else if (isInSpace) {
isInSpace = false;
++numOfWords;
}
}
cout << "Number of chars: " << numOfChars << endl;
cout << "Number of words: " << numOfWords << endl;
return 0;
}

How do I write a function that counts consecutive letters in a string that are identical

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;
}

C++ - Replacing "_" with a character

Using C++, I'm trying to make a hangman game to become better at using C++ and programming in general. Anyways, the issue I'm facing is that I'm not sure how to replace the dashes within a string with the letter the user has guessed.
I think my problem is with the fact the word chosen is randomly chosen from an array and I'm not sure how to go about finding the positions within the randomly chosen string which consists of the guessed character.
I have commented out the area that's causing the issue.
#include <iostream>
#include <array>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <cstddef>
#include <algorithm>
using namespace std;
int main()
{
string words[3] = {"stack", "visual", "windows"};
string guess;
cout << "Welcome to hangman.\n";
cout << "\n";
srand(time(NULL));
int RandIndex = rand() % 3;
string selected = words[RandIndex];
for (int i = 1; i <= selected.size(); i++) {
cout << "_ ";
}
cout << "\n";
cout << "\nType in a letter: ";
cin >> guess;
cout << "\n";
if (selected.find(guess) != string::npos) {
/*for (int i = 1; i <= selected.size(); i++) {
if (selected.find(guess) != string::npos) {
cout << "_ ";
} else {
cout << guess << " ";
}
}*/
} else {
cout << "\nNay!\n";
cout << "\n";
}
cout << "\n";
cout << "\n";
system("PAUSE");
return 0;
}
I was thinking about using the replace() function but the problem I face here is that I'm not replacing the string within selected variable but sort of iterating through the word itself, if that made any sense whatsoever?
Use a second string, that is initialized with the underscores. If the find function doesn't return string::npos it returns the position in the string, and this is the same position you should change in the string with the underscores as well.
You actually need to use a second string to store the "guessed" string; this is because you need to keep track of all the guessed letters and display them.
something like :
string s ="test";
string t=""; //empty string
for(int i=0;i<s.size();i++)
t.append("_"); //initialize the guess string
cout<<t<<'\n';
char c;
cin >> c;
int pos = s.find(c); //get the first occurrence of the entered char
while(pos!=-1) //look for all occurrences and replaced them in the guess string
{
t.replace(pos,1,1,c);
pos = s.find(c, pos+1);
}
I think you need to maintain some extra state while looping - to keep track of which letters have / haven't been guessed.
You could add a new string current_state which is initially set to the same length as the word but all underscores. Then, when the player guesses a letter, you find all instances of that letter in the original word, and replace the underscore with the letter guessed, at all the positions found but in current_state.
First i would initialize a new string to show the hidden word:
string stringToDisplay = string( selected.length(), '_');
Then For each letter given by the user i would loop like this:
(assuming guess is letter)
size_t searchInitPos = 0;
size_t found = selected.find(guess, searchInitPos));
if (found == string::npos)
{
cout << "\nNay!\n";
cout << "\n";
}
while( found != string::npos)
{
stringToDisplay[found] = guess;
searchInitPos = found+1;
found = selected.find(guess, searchInitPos));
}
cout << stringToDisplay;
Hope this will help
I think it should be that:
string words[3] = {"stack", "visual", "windows"};
char guess;
string display;
cout << "Welcome to hangman.\n";
cout << "\n";
srand(time(NULL));
int RandIndex = rand() % 3;
string selected = words[RandIndex];
for (int i = 0; i < selected.size(); i++) {
display.insert(0, "_ ");
}
cout << display;
while(display.find("_ ") != string::npos) {
cout << "\n";
cout << "\nType in a letter: ";
cin >> guess;
cout << "\n";
bool flag = false;
for (int i = 0; i < selected.size(); i++) {
if (selected[i] == guess) {
display.replace(i*2, 1, 1, guess);
flag = true;
}
}
if (!flag) {
cout << "\nNay!\n";
cout << "\n";
} else {
cout << display;
}
}