How to copy a string into a char array with strcpy - c++

I my trying to copy a value into a char.
my char array is
char sms_phone_number[15];
By the way, could tell me if I should write (what the benefic/difference?)
char * sms_phone_number[15]
Below displays a string: "+417611142356"
splitedString[1]
And I want to give that value to sms_from_number
// strcpy(sms_from_number,splitedString[1]); // OP's statement
strcpy(sms_phone_number,splitedString[1]); // edit
I've got an error, I think because splitedString[1] is a String, isn't?
sim908_cooking:835: error: invalid conversion from 'char' to 'char*'
So how can I copy it correctely.
I also tried with sprintf without success.
many thank for your help.
Cheers

I declare spliedString like this
// SlitString
#define NBVALS 9
char *splitedString[NBVALS];
I have that function
splitString("toto,+345,titi",slitedString)
void splitString(char *ligne, char **splitedString)
{
char *p = ligne;
int i = 0;
splitedString[i++] = p;
while (*p) {
if (*p==',') {
*p++ = '\0';
if (i<NBVALS){
splitedString[i++] = p;
}
}
else
{
p++;
}
}
while(i<NBVALS){
splitedString[i++] = p;
}
}
If I do a for with splitedString display, it display this
for(int i=0;i<4;i++){
Serialprint(i);Serial.print(":");Serial.println(splitedString[i]);
}
//0:toto
//1:+4176112233
//2:14/09/19
I also declared and want to copy..
char sms_who[15];
char sms_phone_number[15];
char sms_data[15];
//and I want to copy
strcpy(sms_who,splitedString[0]
strcpy(sms_phone_number,splitedString[1]
strcpy(sms_date,splitedString[2]
I know, I am very confused with char and pointer * :o(

The declaration:
char * SplittedString[15];
Declares an array of pointers to characters, a.k.a. C-style strings.
Given:
const char phone1[] = "(555) 853-1212";
const char phone2[] = "(818) 161-0000";
const char phone3[] = "+01242648883";
You can assign them to your SplittedString array:
SplittedString[0] = phone1;
SplittedString[1] = phone2;
SplittedString[2] = phone3;
To help you a little more, the above assignments should be:
SplittedString[0] = &phone1[0];
SplittedString[1] = &phone2[0];
SplittedString[2] = &phone3[0];
By definition, the SplittedStrings array contains pointers to single characters, so the last set of assignments is the correct version.
If you are allowed, prefer std::string to char *, and std::vector to arrays.
What you need is a vector of strings:
std::vector<std::string> SplittedStrings(15);
Edit 1:
REMINDER: Allocate space for your spliedString.
Your spliedString should either be a pre-allocated array:
char spliedString[256];
or a dynamically allocated string:
char *spliedString = new char [256];

Strings and Chars can be confusing for noobs, especially if you've used other languages that can be more flexible.
char msg[40]; // creates an array 40 long that can contains characters
msg = 'a'; // this gives an error as 'a' is not 40 characters long
(void) strcpy(msg, "a"); // but is fine : "a"
(void) strcat(msg, "b"); // and this : "ab"
(void) sprintf(msg,"%s%c",msg, 'c'); // and this : "abc"
HTH

Related

Pass char array on to a function C++

My goal is to take in a character array and replace specific words such as "class" with the word "video". However, the data in buf array is coming from a web server that has unicode in it, so to my knowledge, I am not allowed to convert the char array into a string because it will mess up much of the data in it (I think).
So, my main question is, how do I pass buf in as an argument to the replaceWords function. Right now I get an error that says,
error: incompatible types in assignment of ‘char*’ to ‘char [256]’
char buf[256];
buf = replaceWords(buf);
char * replaceWords(char* buf) {
char badWord1[] = "class";
char * occurrence = strstr(buf, badWord1);
strncpy(occurrence, "video", 5);
return buf;
}
The error is caused by buf = replaceWords(buf);. This tries to assign the function return value (char*) to an array and that's not valid syntax.
Your code passes the array to the function and the function changes the character string in-place. You don't need the return value from the function. In fact, the function could just be defined as returning void and then you can remove the return statement.
Note: you should probably add some error checking. What happens if the badWord1 string is not found and strstr() returns NULL?
Look at this code:
#include <bits/stdc++.h>
using namespace std;
void replaceWords(char buf[]) {
char badWord1[] = "class";
char * occurrence = strstr(buf, badWord1);
strncpy(occurrence, "video", 5);
}
int main() {
char temp[5];
temp[0] = 'c';
temp[1] = 'l';
temp[2] = 'a';
temp[3] = 's';
temp[4] = 's';
replaceWords(temp);
cout << temp << endl;
return 0;
}
It will work as you intend. When you pass char buf[] you are passing a reference to the array you want to modify. That way you can modify it in the function and it will be modified everywhere else in the program. There's not need to do additional assignment.

Reversing a string in C++ using pointers

void reverse(char[] x) {
char* pStart = x;
char* pEnd = pStart + sizeof(x) - 2;
while(pStart < pEnd) {
char temp = *pStart;
*pStart = *pEnd;
*pEnd = temp;
pStart++;
pEnd--;
}
}
int main() {
char text[] = ['h','e','l','l','o'];
reverse(text);
cout << text << endl;
return 0;
}
I am new to C++ and stack overflow.
I am trying to reverse a string using pointers... I don't quite understand what I did wrong. Please help me out.
Additional question: What is the difference between a string and an array of characters?
sizeof(x) with x being a parameter of type char[] of a function does not give you the number of characters in the string but the size of a char*, probably 8 on a 64 bit system. You need to pass a C-String and use strlen(x) instead. Write char text[] = {'h','e','l','l','o','\0'} or char text[] = "hello" in main.
Note that sizeof() needs to be evaluatable at compile time; this is not possible on arrays with undetermined size like char[]-typed function arguments. When using sizeof on a variables like your char text[] = {'h','e','l','l','o'}, however, sizeof(text) will result in the actual size of the array.
char x[] is the same as char* x and the sizeof(x) is therefore the size of a pointer. So, because you cannot calculate the size of an array outside of the block it is declared in, I would eliminate that part from your function.
It would be much easier to provide the function with pointers to the first and last characters to be replaced:
void reverse(char* pStart, char* pEnd)
{
while (pStart < pEnd)
{
char temp = *pStart;
*pStart = *pEnd;
*pEnd = temp;
pStart++;
pEnd--;
}
}
So now it is quite easy to call this function - take the address (using ampersand &) of the the relevant characters in the array: &text[0] and &text[4].
To display an array of characters, there is a rule, that such "strings" HAVE to have after the last character a NULL character. A NULL character can be written as 0 or '\0'. That is why it has to be added to the array here.
int main()
{
// char text[] = "hello"; // Same like below, also adds 0 at end BUT !!!in read-only memory!!
char text[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
reverse(&text[0], &text[4]);
std::cout << text << std::endl;
return 0;
}

Copy specific range of 2 Dimensional Char[][] Array to char * or std::string

Assuming you read the title, here's a little example in pseudo code:
char inputChar[5][20];
{put data in array obviously}
char * outputChar;
copy(inputChar[2][7], inputChar[2][18], outputChar);
printf("%s", outputChar);
or optionally (although I prefer the above version):
char inputChar[5][20];
{put data in array obviously}
std::string outputString;
copy(inputChar[2][7], inputChar[2][18], outputString);
cout outputString; //I don't know how to use std::strings with printf
I've tried std::copy and memcpy but I can't get it to work. The result either gives me random characters that aren't part of the string, or just results in compiler errors due to me not understanding the syntax fully.
EDIT:
Here is the actual code I'm using:
(assume for this example that storeMenu already has data assigned to it)
int line = 0
int frame5 = 11;
char storeMenu[9][13];
char * temp1 = new char[12];
char * temp2 = new char[12];
std::copy(&storeMenu[line+1][0], &storeMenu[line+1][frame5-10], temp1);
std::copy(&storeMenu[line][frame5-10], &storeMenu[line][12], temp2);
To use std::copy you need a pointer to the location of the character, you are passing the character itself here. You also need to initialize outputChar.
char inputChar[5][20] = {"abc","def","ghi01234567890","jkl"};
char * outputChar = new char[20];
auto last = copy(&inputChar[2][0], &inputChar[2][5], outputChar);
*last = '\0';
printf("%s\n", outputChar);
Alternatively using std::string:
char inputChar[5][20] = {"abc","def","ghi01234567890","jkl"};
string outputChar;
copy(&inputChar[2][0], &inputChar[2][5], back_inserter(outputChar));
printf("%s\n", outputChar.c_str());
Using inputs as std::string too:
string inputChar[5] = {"abc","def","ghi01234567890","jkl"};
int fromChar = 2; // from (inclusive) ^ ^
int toChar = 5; // to (exclusive) ^
string outputChar;
copy(inputChar[2].begin()+fromChar, inputChar[2].begin()+toChar, back_inserter(outputChar));
printf("%s\n", outputChar.c_str());
cout << outputChar << endl;

c++ code type substition fail

I have this code, but is impossible to compile with g++ or msvc. I am trying to make a custom type CharNw that I can use it as string, in existing all string routines or pass as argument all existing functions:
#include <string.h>
#include <stdio.h>
void fx(unsigned int x)
{
/*this is the reason of all this
but is ok, not is problem here */
.....
}
class CharNw
{
int wt;
char cr;
public:
CharNw() { wt = -1; cr = '\0'; }
CharNw( char c) { if wt > 0 fx( (unsigned int) wt); cr = c; }
operator char () { if wt > 0 fx( (unsigned int) wt); return cr ;}
assgn( int f) { wt = f;}
};
int main(void)
{
CharNw hs[40]; //it is ok
CharNw tf[] = "This is not working, Why?\n";
char dst[40];
strcpy(dst, tf); //impossible to compile
printf("dst = %s, tf = %s", dst, tf); //too
return 0;
}
Can help me?
Line by line.
CharNw hs[40]; //it is ok
The above is an array of CharNw objects with a capacity of 40 elements. This is good.
CharNw tf[] = "This is not working, Why?\n";
On the right hand side (RHS) of the assignment, you have a type char const * const* and on the left you have an array ofCharNw. TheCharNw` is not a character, so you have a problem here. Prefer to have both sides of an assignment to have the same type.
char dst[40];
An array of characters. Nothing more, nothing less. It has a capacity of 40 characters. The dst array is not a string. You should prefer to use #define for your array capacities.
strcpy(dst, tf); //impossible to compile
The strcpy requires both parameters to be pointers to char. The left parameter can be decomposed to a pointer to the first char of the array. The tf is an array of CharNw which is not compatible with an array of char nor a pointer to char.
printf("dst = %s, tf = %s", dst, tf); //too
The printf format specifier %s requires a pointer to a character, preferably a C-Style, nul terminated array (or sequence) of characters. The tf parameter is an array of CharNw which is not an array of characters nor a pointer to a single character or a C-Style string.
Edit 1: Conversion Operators
The method operator char () in your class converts a character variable to a CharNw variable. It does not apply to pointers nor arrays.
You would need some messy pointer conversion functions.
Here is an examples:
const unsigned int ARRAY_CAPACITY = 40U;
const char text[] = "I am Sam. Sam I am."
CharNw tf[ARRAY_CAPACITY];
for (unsigned int i = 0U; i < sizeof(text); ++i)
{
tf[i] = text[i]; // OK, Converts via constructor.
}
for (unsigned int i = 0U; i < sizeof(text); ++i)
{
printf("%c", tf[i]); // The tf[i] should use the operator char () method.
}
A better approach is to declare a class using std::basic_string, rather than trying to squeeze your class into the C-Style string functions.
For example:
class StringNw : public std::basic_string<CharNw>
{
};

Remove items from a char * C++

I am trying to remove characters from a char pointer and would like to store them back in a new char pointer variable let's say "temp". So I would have something like this:
char *test = "1#2#3$4%5^6&7*8!9#1#0";
char *temp = "";
then remove the "#,#,$,%,^,*,!,#,#," and place the new values of "12345678910" into *temp. This would make temp be equal to "12345678910".
Is this possible?
I have been doing this with string but I really need to do this with the char pointers. Here is how I have done this with string:
std::string str("1#2#3$4%5^6&7*8!9#1#0");
std::string temp("");
char chars[] = "##$%^&*!";
for (unsigned int i = 0; i < strlen(chars); ++i)
{
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());
}
temp = str;
So you see here I am doing this all will strings but I just cannot seem to get away with asigning a char * variable like test to a string because its an illegal conversion. However why am I able to set my char * variables equal to string like so?
char *test = "123456789";
However this is illegal?
std::string str("1#2#3$4%5^6&7*8!9#1#0");
char chars[] = "#";
for (unsigned int i = 0; i < strlen(chars); ++i)
{
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());
}
char *test = str; //Illegal point
Thank you for your time.
change
char *test = str;
into:
char *test = str.c_str();
c_str is a method that creates c style char array from original string for you.
EDIT: this is a more safe way, a copy of the c string will be obtained:
#include <cstring>
#include <cstdlib>
...
char *test = strdup(str.c_str());
... // process the string
free(test);
Here you have a reference to std string class.
Manpage for strdup.
Anything you can do with iterators you can also do with pointers to an array. Say, an array of chars:
char str[] = "1#2#3$4%5^6&7*8!9#1#0";
char chars[] = "#";
for (unsigned int i = 0; i < strlen(chars); ++i)
{
*std::remove(str, str+strlen(str), chars[i])=0;
}
Notice that I used the fact that std::remove returns an iterator (in this case char*) to the "one after last" element and set that char to 0 - making sure it stays a zero-delimited string