Removing a specific element from a string in C++ - c++

I was trying to remove X from a given string, the code compiles and runs but there is no output shown. I guess the problem is where I have to use the 'cout' operator.
Here is my Code:
#include<iostream>
#include<bits/stdc++.h>
#include<string.h>
using namespace std;
void removeX(char str[])
{
if(str[0]='\0')
{
cout<<str;
}
if(str[0]!='x'||str[0]!='X')
{
removeX(str+1);
}
else
{
for(int i=0;i!='\0';i++)
{
str[i]=str[i+1];
}
removeX(str+1);
}
}
int main()
{
char a[]="MALCOLM X";
removeX(a);
return 0;
}

You have a few issues in your code, the ones I can spot right away are:
if(str[0]='\0') - this is an assignment, not a comparison. Your entire string will be replaced with \0-characters - no characters will be skipped because this:
if(str[0]!='x'||str[0]!='X') is always true. Ask yourself if x is different from x (false) OR X (true). False or true = true.
The check should be implemented something like (str[0] != 'x' && str[0] != 'X').
Edit: One more issue.
The overall logic will not work (-ish). The part where you run through the string and compress it is correct enough. But you try to run to the end and then print the string, however at that point you are only holding the end of the string (the null termination), so no matter what else you have done you will only print that (aka. print nothing).
Instead, once you are done compressing the xs out of the string, you need to return to the beginning of the string and then print that. The easy way is to print in main, or you can split your function into an outer+inner function like:
void outer_removeX(str) {
removeX(str);
print(str);
}
Or you could add an extra variable to the recursion that allows you to return to the first call in the chain and then print there.
However, only printing the end will not work.

try the following code:
#include<iostream>
#include<bits/stdc++.h>
#include<string.h>
using namespace std;
void removeX(char str[],int j)
{
if(str[j]=='\0')
{
cout<<str;
}
else if(str[j]!='x' && str[j]!='X')
{
removeX(str,++j);
}
else
{
for(int i=j;str[i]!='\0';i++)
{
str[i]=str[i+1];
}
removeX(str,j);
}
}
int main()
{
char a[]="MAxLCOLM X";
removeX(a,0);
return 0;
}

Related

My c++ loop doesn't stop when i tell it to do it through the console

I have made a loop which should encrypt the phrases I tell it to, but didn't finish because of the problem. It should detect when I say "stop" in the console and shut down the loop. It doesn't work.
What i want it to do is to detect if i said stop and break the loop. I shouldn t get any random missfires from getting the letters s t o p from other words. As you can see, every time there is a letter out of order, it resets the vectors which locks all of the ifs until 'c' gets the correct letters in the correct order.
using namespace std;
int main()
{
char c,v[5];
int i=0;
while(i!=1)
{
cin.get(c);
if(c=='s' or v[1]=='s')
{
v[1]='s';
if(c=='t' or v[2]=='t')
{
v[2]='t';
if(c=='o' or v[3]=='o')
{
v[3]='o';
if(c=='p' or v[4]=='p')
{
v[4]='p';
v[1]=v[2]=v[3]=v[4]=0;
i=1;
}
else
v[1]=v[2]=v[3]=0;
}
else
v[1]=v[2]=0;
}
else
v[1]=0;
}
cout<<c;
if (i==1)
break;
}
return 0;
}
That should the work and is not indented hell code. It assumes that you are entering one character at a time.
#include <iostream>
int main(int argc, char const *argv[])
{
char keyword[] = "stop";
char* matching_char = keyword;
char char_from_user;
while(*matching_char != '\0')
{
std::cin.get(char_from_user);
// Reset if different character
if(*matching_char != char_from_user)
matching_char = keyword;
// Increment position of match
if(*matching_char == char_from_user)
++matching_char;
// Ignore rest in buffer
std::cin.ignore();
}
return 0;
}
Following your logic, you just need to assign the v array values after each if/else condition otherwise it will just get immediately reassigned to 0. For example, you first assign v[1] = 's', and then right after you assign it to v[1] = 0, because the if returns false in first iteration. The following code should solve the problem.
#include <iostream>
using namespace std;
int main()
{
char c,v[5];
int i=0;
while(i!=1)
{
cin.get(c);
if(c=='s' || v[1]=='s')
{
if(c=='t' || v[2]=='t')
{
if(c=='o' || v[3]=='o')
{
if(c=='p' || v[4]=='p')
{
v[4]='p';
v[1]=v[2]=v[3]=v[4]=0;
i=1;
}
else
v[1]=v[2]=v[3]=0;
v[3]='o';
}
else
v[1]=v[2]=0;
v[2]='t';
}
else
v[1]=0;
v[1]='s';
}
if (i==1)
break;
}
return 0;
}

Character replacement not working

enter image description hereI have the following code that is supposed to replace instances of pi (3.14) with the word "pi". For example, "x3.14 3.14 3.14xx" should be turned into "xpi pi pixx". However, my code isn't doing that; why doesn't it work, and how would I fix it?
#include<iostream>
#include<cstring> //dsfsdf
#include<string>
#include<cstdio>//sdfdsf
using namespace std;
void replacepi(char *arr,int i)
{
//base
if(arr[i]=='\0')
{
cout<<arr<<endl;
return;
}
//recc
if(arr[i]=='3' && arr[i+1]=='.' && arr[i+2]=='1' && arr[i+3]=='4')
{
arr[i]='p';
arr[i+1]='i';
for(int j=i+4;arr[j]!='\0';j++)
arr[j-2]=arr[j];
arr[strlen(arr)-2]='\0';
}
replacepi(arr,i+1);
}
int main() {
long int n;
cin>>n;
for(int i=0;i<n;i++)
{
char arr[1000];
cin.getline(arr,sizeof(arr));
replacepi(arr,0);
}
return 0;
}
Looks like a job for regex_replace. Given you've read your input into arr you can just dump the replacement to the console like this:
regex_replace(ostream_iterator<char>(cout), cbegin(arr), cend(arr), regex("3\.14"), "pi")
Live Example
Naturally arr should be a string as in the example rather than a char[], as given any size char[] the input may be larger, a string will always work.

Simple recursive C++ code keeps crashing

So I'm teaching myself C++ and I'm struggling to understand why this code keeps crashing. I've identified that this line: string str = to_string(n) is probably incorrect. But I'm not seeing the other errors for why it's crashing.
#include <iostream>
#include <string>
using namespace std;
void write_vertically(int n)
{
string str = to_string(n);
if (str.length()>=0)
{
cout<<stoi(str.substr(0,1))<<endl;
write_vertically(stoi(str.substr(1,str.length())));
}
}
int main( )
{
write_vertically(1234567890);
return 0;
}
You are having a Stack Overflow! And you're on the perfect website to find a solution to that.
In the line string str = to_string(n);
No matter the value of n, to_string is going to return a non-empty string, which could be "0", "6" or "1653", whatever.
The end condition for your recursion is if (str.length() >= 0) is false.
However, as stated above that is never false.
What did you intend the end condition of your recursion to be? Maybe we can help you with that.
Edit: It turns out that the code should crash before going into a stack overflow, because it would end up calling stoi with an empty string, which makes it throw an std::invalid_argument. However, there was still an infinite recursion problem, so I will keep my answer up.
You are calling stoi("") at the end
#include <iostream>
#include <string>
using namespace std;
void write_vertically(int n){
string str = to_string(n);
cout<<stoi(str.substr(0,1))<<endl;
if (str.length()>1)
write_vertically(stoi(str.substr(1,str.length())));
}
int main( ) {
write_vertically(1234567890);
return 0;
}
https://ideone.com/YfYhZw
You are doing a lot of (unnecessary) type conversion. Here's a way to accomplish your goal without using strings.
#include <iostream>
using namespace std;
void write_vertically( unsigned int n ) {
unsigned int d = n % 10;
n /= 10;
if( n )
write_vertically( n );
cout << d << endl;
}
int main() {
write_vertically(1234567890);
return 0;
}
You have to change your recursion condition as follows:
if (str.length()> 0) {
cout<<stoi(str.substr(0,1))<<endl;
if(str.length() > 1)
write_vertically(stoi(str.substr(1,str.length())));
}
}
Demo: http://coliru.stacked-crooked.com/a/ecd26e57c45cea2b

C++: Using Recursion Transform characters

I am making a Program which will convert a string using recursion.
The method replaces all occurrences of upper case characters with "1" all occurrences of "o" with 2 and all occurrences of "r" with a.
Requirement: The Recursive function should take only one Parameter that is the input string and returns the converted string.
Below is my code:
#include<iostream>
#include<conio.h>
#include<string>
#include<string.h>
using namespace std;
int count=0;
string convert(string a)
{
int b=a.length();
if(b>=count)
{
if (isupper(a[b-(b-count)]))
{
a.replace(b-(b-count),1,"1");
convert(a);
}
else if (a[b-(b-count)]=='o')
{
a.replace(b-(b-count),1,"2");
convert(a);
}
else if(a[b-(b-count)]=='r')
{
a.replace(b-(b-count),1,"a");
convert(a);
}
}
else
return a;
}
void main()
{
string a;
a="ABCrroo";
int l=a.length();
cout<<convert(a);
getch();
}
You've defined convert() as returning a std::string but there are four places inside the function where you make a recursive call and do nothing with the return value. You have to do something if you want to pass the result of each recursive call back up the call stack.
I modified your code and changed the four bare convert(a); lines to return convert(a); and it outputs "212a212a212a" which I think is the desired result.
It also looks like you are using an index one past the end of the string. The condition if(b>=count) would allow your code to use an index outside the valid range of 0..length-1. Try changing it to just if(b>count).
#include<iostream>
#include<string>
#include<string.h>
string convert1(string a, int pos);
using namespace std;
int count=0;
string convert1(string a, int pos)
{
if(pos < a.length())
{
if(isupper(a[pos])) a.replace(pos, 1, "1");
else if(a[pos]=='o') a.replace(pos, 1, "2");
else if(a[pos]=='r') a.replace(pos, 1, "a");
convert1(a, ++pos);
}
else return a;
}
int main()
{
string a="oYoroCoroSor";
cout << a << endl;
int l=a.length();
cout<< convert1(a, 0) << endl;
return 0;
}

Segmentation fault(SIGSEGV) in my code

Im getting Segmentation fault(SIGSEGV) for many problems that iv solved in spoj and other websites. Im giving the problm statement link and code. Can anybody tell me the mistakes that iv done below.
Problem :
http://goo.gl/CVROl
Thanks in advance.
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int main()
{
char a;
string final,dummy;
int t,h,p,k,z;
scanf("%d",&t);
while(t)
{
cin>>a>>h>>p;
final=a;
for(int i=0;i<h;i++)
{
k=0;
for(int j=0;final[j]!='\0';j++)
{
if(final[j]=='a')
{
dummy[k]='a';
dummy[k+1]='b';
k+=2;
}
else
{
dummy[k]='b';
dummy[k+1]='a';
k+=2;
}
}
final=dummy;
}
printf("%c\n",final[p-1]);
t--;
}
return 0;
}
As pointed out by sstn, you did not allocate memory for dummy. Since it's a string and it looks like you just want to append characters to it, you can do:
for(int j=0;j < final.size();j++)
{
if(final[j]=='a')
{
dummy.push_back('a');
dummy.push_back('b');
}
else
{
dummy.push_back('b');
dummy.push_back('a');
}
}
final=dummy;
final is of type std::string, which aren't null terminated.
In your for loop: for(int j=0;final[j]!='\0';j++) you're checking for the end of the string as you would do in C (which a char* -- null terminated string), but in C++ you should iterate over string characters in some other ways: using an iterator, counting up the string size or something.
A fast quick to this problem (don't know whether there are others) is to get the null terminated char* representation of final: final.c_str() and iterater over it as you're doing.