Convert char to const char* String Insert C++ - c++

I have a problem with String Insertion because, I can not add a char, just a const char. How can i easily convert it?
The compiler just accept like this:
b.insert(i,"a");
But i want like this:
b.insert(i,b[ii]);
Full Code:
#include <stdio.h>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string a,b;
int aa=0;
cin >> a;
b=a;
for(int i=0;i<a.length()+1;i++)
{
for(int ii=0;ii<a.length();ii++)
{
b.insert(i,a[ii]);
if (b == string(b.rbegin(), b.rend()))
{
cout << b << endl;aa=1;
break;
}
b.erase (b.begin()+i);
}
if(aa=1)break;
}
if(aa==0)
cout << "NA" << endl;
return 0;
}

See the documentation for std::string::insert. The version that takes a single char also needs a count argument.
b.insert(i,1,b[ii]);

You should use the following overload of std::string::insert:
basic_string& insert( size_type index, size_type count, CharT ch );
See http://en.cppreference.com/w/cpp/string/basic_string/insert

Related

How can I replace multiple characters with just one (C++)?

We have a char. We need to replace all ab characters from our char with the letter c.
Example we have :
abracadabra
the output will be :
cracadcra
I tried to use replace() function from C++, but no success.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string test;
cin>>test;
for(int i=0;i<(strlen(test)-1);i++)
{
if((test[i]=='a')&&(test[i+1]=='b')){
test.replace( test[i], 'c' );
test.replace( test[i+1] , ' ' );
}
}
cout << test << endl;
return 0;
}enter code here
You can use C++11 regex:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "abracadabra";
std::regex r("ab");
std::cout << std::regex_replace(str, r, "c") << "\n"; // cracadcra
}
Problem:
That is not the syntax of std::string::replace.
Solution:
As is mentioned here the syntax is std::string::replace(size_t pos, size_t len, const string& str). Do test.replace(i, 2, "c" ) instead of test.replace(test[i],'c').
Or use regular expressions as dtell pointed.
Adittional information:
using namespace std; is considered a bad practice (More info here).
You should use std::string::size instead of strlen when you're working with std::string.
To work with std::string you should use #include <string> instead of #include <cstring>.
Full code:
#include <iostream>
int main()
{
std::string test;
std::cin >> test;
for(unsigned int i = 0; i < test.size() - 1; i++)
{
if((test[i]=='a') && (test[i+1]=='b'))
{
test.replace(i, 2, "c" );
}
}
std::cout << test << std::endl;
return 0;
}
The simplest thing you can do by using the standard library is first to find ab and then replace it. The example code I wrote is finding string ab unless there is None in the string and replacing it with c.
#include <iostream>
#include <string>
int main()
{
std::string s = "abracadabra";
int pos = -1;
while ((pos = s.find("ab")) != -1)//finding the position of ab
s.replace(pos, sizeof("ab") - 1, "c");//replace ab with c
std::cout << s << std::endl;
return 0;
}
//OUTPUT
cracadcra

istringstream-function string_to_int cannot take c-str, why?

I learned a helper function that can convert strings to integers:
int string_to_int(string s)
{
istringstream instr(s);
int n;
instr>>n;
return n;
}
It's mentioned that the argument s cannot be c-str string, why is this the case?
But you can pass a C style string.
The reason for that is because the std::string constructor can implicitly accept a CharT* (Char type, which is char in this case) as a parameter. Thus, something like the following would work:
#include <iostream>
#include <sstream>
using namespace std;
int string_to_int(string s)
{
istringstream instr(s);
int n;
instr>>n;
return n;
}
int main()
{
const char* test = "12345";
std::cout << string_to_int(test) << "\n"; // Outputs 12345
std::cout << string_to_int("122") << "\n"; // Outputs 122
}

ERROR deprecated conversion from string constant to 'char*'

I'm stuck with error message deprecated conversion from string constant to 'char*'
What I tried to do here is to assign "First", "Last" to cfoo1 and make cfoo2 equal to cfoo1. Lastly, display cfoo1 and cfoo2 to standard output.
#include <iostream>
#include <cstring>
#include "cfoo.h"
using namespace std;
CFoo :: CFoo(char first[], char last[]){
m_first[BUF] = first[BUF];
m_last[BUF] = last[BUF];
}
void CFoo :: WriteFoo(){
cout << m_first[BUF] << ", " << m_last[BUF];
}
#ifndef CFOO_HEADER
#define CFOO_HEADER
#include <iostream>
#include <cstring>
using namespace std;
const int BUF = 256;
class CFoo{
public:
CFoo(char first[], char last[]);
void WriteFoo();
private:
char m_first[BUF];
char m_last[BUF];
};
#endif
#include <iostream>
#include "cfoo.h"
using namespace std;
int main(){
CFoo foo1("Jong", "Yoon");
CFoo foo2 = foo1;
cout << "foo1 = ";
foo1.WriteFoo();
cout << endl;
cout << "foo 2 = ";
foo2.WriteFoo();
cout << endl;
return 0;
}
There are two issues:
Using string literals (which are of type char const*) to call a function that expects char[].
Trying to assign to char arrays.
Fixes:
Change the constructor to:
CFoo(char const* first, char const* last);
Change its implementation to:
CFoo(char const* first, char const* last)
{
// Make sure to copy at most BUF-1 characters
// to m_first and m_last.
m_first[0] = '\0'
strncat(m_first, first, BUF-1);
m_last[0] = '\0'
strncat(m_last, last, BUF-1);
}
You also need to change the implementation of CFoo::WriteFoo() to use the entire string
void CFoo::WriteFoo()
{
cout << m_first << ", " << m_last;
}
Also,
Accessing m_first[BUF] or m_last[BUF] is an error since the maximum value of a valid index to access those arrays is BUF-1.

C++ function overloading cannot identify char

When I input two integers, the output is correctly their difference. However when I enter a string and a char, instead of returning how many times the char appears in the string, it returns -1, which is the out put for error. Could anyone please help me? It's just my second day learing c++...
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
void mycount(int a, int b)
{
std::cout<< a - b <<std::endl;
}
void mycount(char str[], char s[])
{
int len,i;
int sum=0;
len = strlen(str);
for (i=0;i<len;i++){
if (strncmp(&str[i],&s[0],1) == 0){
sum = sum + 1;
};
};
printf("results: %d times\n",sum);
}
int main()
{
int a,b;
char c[200],d;
if(std::cin>> a >> b){
mycount(a,b);
}
if(std::cin>> c[200] >> d){
mycount(a,b);
}
else{
std::cout<< "-1" <<std::endl;
}
std::cin.clear();
std::cin.sync();
}
Hint - what will this program print?
#include <iostream>
using namespace std;
int main()
{
char c[200],d;
cout << sizeof(c) << endl;
cout << sizeof(d) << endl;
return 0;
}
Answer:
200
1
That declaration does not do what you think it does - c is an array of 200 chars, d is a single char. It's a feature of the C declaration syntax, same as:
int *c, d;
c is a pointer to int, d is an int.
Since you are doing C++, why not make your life easier and use std::string instead?
A few changes should fix your problems. First when inputting an array with cin use getline and call ignore right before hand. I find it easier to pass s as a char instead of an array of size one make sure your call your second my count with c and d instead of a and b.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
void mycount(int a, int b)
{
std::cout<< a - b <<std::endl;
}
void mycount(char str[], char s)
{
int len,i;
int sum=0;
len = strlen(str);
for (i=0;i<len;i++){
if (strncmp(&str[i],&s,1) == 0){
sum = sum + 1;
};
};
printf("results: %d times\n",sum);
}
int main()
{
int a,b;
char c[200],d;
if(std::cin>> a >> b){
mycount(a,b);
}
std::cin.ignore();
if(std::cin.getline (c,200) && std::cin >> d){
mycount(c,d);
}
else{
std::cout<< "-1" <<std::endl;
}
std::cin.clear();
std::cin.sync();
}
These changes should fix it.

Error for pointer to member in C++

Header file
#include <iostream>
#include <cstring>
const unsigned MaxLength = 11;
class Phone {
public:
Phone(const char *phone) {
setPhone(phone);
}
void setPhone(const char Phone[ ]);
const char* getPhone();
private:
char phone[MaxLength+1];
};
Cpp file
#include "Phone.h"
#include <iostream>
#include <ctype.h>
#include <cstring>
using namespace std;
bool checkNum(char num[]);
void Phone::setPhone(const char Phone[ ]) {
strncpy(phone, Phone, MaxLength);
phone[MaxLength] = '\0';
}
const char* Phone::getPhone() {
return phone;
}
int main() {
Phone i1("12345678901");
cout << i1.getPhone() << endl;
if (checkNum(i1.getPhone))
cout << "Correct" << endl;
else
cout << "Invalid Wrong" << endl;
}
bool checkNum(char num[]) {
bool flag = true;
if (isdigit(num[0]) == 0)
flag = false;
return flag;
}
When I tried to compile, I get this error:
error C3867: 'Phone::getPhone':
function call missing argument list;
use '&Phone::getPhone' to create a
pointer to member
I'm getting an error on this line "if (checkNum(i1.getPhone))". I created a Phone object and what I am trying to do is use the function checkNum to see if the first index of the array is a number. Am I referencing the object wrong? Should I use indirect selection operator instead? Any idea what I am doing wrong?
Thanks
You are missing a pair of parentheses after getPhone in if (checkNum(i1.getPhone)); it should be if (checkNum(i1.getPhone())).
The line:
if (checkNum(i1.getPhone))
should be
if (checkNum(i1.getPhone()))