Concatenate a char* to a string

272 views Asked by At

I have to concatenate all the numbers in a string to another one.

char *cif = "1234567890";
char s[100], s1[40] = "", s2[40] = "";
cin.getline(s, 100);

for (int i=0; i<strlen(s); i++)
   if (strchr(cif, s[i]))
       strcpy(s1+1, s[i]);

But I get:

error: invalid conversion from 'char' to 'const char*' [-fpermissive]|

2

There are 2 answers

0
463035818_is_not_an_ai On

You can use std::string and its operator+ to concatenate strings:

#include <iostream>
#include <string>

int main() {

    const char *cif = "1234567890";
    
    std::string cifs{cif};
    std::string other{"foo"};
    std::string concatenated= other + cifs + other;
    std::cout << concatenated;
}

Live Demo

In your code its not actually clear what you want to concatenate with what. I hope the above is clear enough to concatenate any string with any other. Note that non-const pointers to string literals is no longer allowed since C++11 and you need a const char*.

1
Lundin On

Doing this the C way in C++ is kind of self-torture since string handling in C is very hands-on and error prone. Someone already posted an example how to better do this using C++.

But if insisting on doing it the C way, you have a bunch of problems here:

  • strcpy is the wrong way to copy a single character. Just assign it s1[index] = s[i];
  • strcpy(s1+1, s[i]); is a syntax error because s[i] is not a pointer, but a single character. This is the reason for your compiler error. But as mentioned above, using strcpy was the wrong thing to begin with.
  • Rather than using strchr on a string of digits, you could use isdigit from <ctype.h>.
  • char *cif = "1234567890"; is wrong in C and C++ both, because string literals are read-only and therefore a pointer to one should always be const qualified no matter language. C++ is stricter than C here since it made string literals type const char[], while they remain char[] in C (but are still read-only).
  • Calling i<strlen(s) inside the loop condition is bad practice, since in theory a bad compiler could call strlen repeatedly in that case, leading to bad performance. Very old compilers struggle with this, but modern ones will optimize it. Still, you should avoid placing function calls of any kind there.

Just for completeness, this is what the fixed C code would look like:

#include <string.h>
#include <stdio.h>
#include <ctype.h>

int main (void)
{
  char s[100]="1337 something666something lalala 42 ", s1[40] = "";
  size_t s1_count=0;
  size_t length = strlen(s);

  for (size_t i=0; i<length; i++)
  {
    if (isdigit(s[i]))
    {
      s1[s1_count] = s[i];
      s1_count++;
    }
  }
  puts(s1);
}

But again, in C++ you should avoid manual string handling like this - use std::string (or maybe std::stringstream, which is a handy little tool for all your string formatting needs).