Pass char array on to a function C++ - 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.

Related

Copying char* with char symbol

I am trying to copy a char* and char symbol into a new char* , however the desired result after copying is wrong.
char* name = "someData";
char symbol ='!';
int size1 = strlen(name);
int size2 = 1;
int newSize = size1 + size2 + 1;
char* res = new char[newSize];
strcpy(res,name);
const char* symbolPointer = &symbol;
strcat(res, symbolPointer);
cout<<*res;
I expect the result to be "someData!" , however it is only "s" , where is my mistake?
char* name = "someData";
This is an ill-formed conversion in C++ (since C++11). I recommend to not point to string literals with pointer to non-const.
const char* symbolPointer = &symbol;
strcat(res, symbolPointer);
Both arguments of std::strcat must be null terminated. symbolPointer is not a pointer to a null terminated string. Because the pre-condition of std::strcat is violated, the behaviour of the program is undefined.
cout<<*res;
res is a pointer to the first character of the string. By indirecting through the pointer to first character, you get the first character. That is why you see the first character (in case the undefined behaviour hasn't caused the program to do something completely different).
Lastly, the program leaks the allocated res.
Here is a fixed example:
std::string name = "someData";
name += '!';
std::cout << name;
The problem is the following:
cout<<*res;
This is equivalent to:
cout << res[0];
It prints just the first character of the output. Use
cout<<res;
Try it this way:
const string name = "someData";
const char symbol ='!';
string res = name + symbol;
cout << res;
You should avoid the legacy C nul-terminated string handling functions. You should avoid using new directly in your code.
The observed result you are asking about is due to you writing *res (a single character) instead of res (a pointer to the first character) in the output statement. But the code was buggy besides that, as strcat will copy until it finds the terminator, so it will overwrite some unknown amount of memory beyond what you allocated.
symbolPointer should end with null character, because strcat requires 0-terminated string.
So if you want to continue on your way,
(not a good idea but)
You can add this before strcat.
*(symbolPointer+1) = 0;
#include <iostream>
#include <cstring>
int main() {
char name[] = "someData";
char symbol ='!';
int size1 = strlen(name);
int size2 = 1;
int newSize = size1 + size2 + 1;
char* res = new char[newSize];
strcpy(res,name);
char* symbolPointer = &symbol;
*(symbolPointer + 1) = 0;
strcat(res, symbolPointer);
cout<<res;
return 0;
}

How can I copy the contents of string to an array of char c++?

So I have this issue
//This holds 5 messages submitted prev by the user, temporarily stored
string arrayOfMessages[5];
lets say
arrayOfMessages[0]="This is my message"//The message in the first position.
I need to copy arrayOfMessages[0] to an array of char like this one;
char message [20];
I tried using strcpy(message,arrayOfMessages[0]) but I get this error :
error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'|
Anyone know how I can accomplish this or if I'm doing something wrong, I cant set the string to be a const char bc the message was imputed prev by the user so it changes every time you run the program thus cannot be a constant variable.
There are many ways of doing it
By using the c_str() function of the string class
string message = "This is my message";
const char *arr;
arr = message.c_str();
By copying all the characters from the string to the char array
string message = "This is my message";
char arr[200];
for(int i = 0; i < 200 && message[i] != '\0'; i++){
arr[i] = message[i];
}
Be careful with the array sizes if you use the second approach.
You can also make it a function in order to make it easier to use
void copyFromStringToArr(char* arr, string str, int arrSize){
for(int i = 0; i<arrSize && str[i] != '\0'; i++){
arr[i] = str[i];
}
}
So in your case you can just call the function like this:
copyFromStringToArr(message,arrayOfMessages[0],20);
Also I am sure there are many more ways to do it but these are the ones I would use.
To copy the contents of std::string into a char[], use c_str():
std::string str = "hello";
char copy[20];
strcpy(copy, str.c_str());
But the datatype of copy must be only char* and not const char*. If you want to assign it to a const char*, then you can use direct assignment:
std::string str = "hello";
const char *copy = str.c_str();

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;

How to copy a string into a char array with strcpy

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

C++ not printing as expected with my own string copy function

sorry for another string copy question.. but I really can't find the reason why in my code, strTo can be printed, but strFinal can't in neither way.
cout << strTo << endl;
cout << strFinal << endl;
while (*strFinal != '\0') {
cout << *strFinal++;
}
Appreciated if someone can point it out where I misunderstood about pointers and arrays! Thanks!
#include <iostream>
using namespace std;
char *str_copy (const char *strFrom, char *strTo)
{
while (*strFrom != '\0') {
*strTo++ = *strFrom++;
}
*strTo = '\0';
return strTo;
}
int main()
{
char strFrom[]="abc123";
char strTo[10];
char *strFinal = str_copy(strFrom, strTo);
cout << strTo << endl;
cout << strFinal << endl;
while (*strFinal != '\0') {
cout << *strFinal++;
}
return 0;
}
Additional Question:
I don't know the reason when I put the code in main function like this:
char strFrom[]="abc123";
char strTo[10];
strTo = str_copy(strFrom, strTo);
Then complier said:
main.cpp:18: error: array type 'char [10]' is not assignable
strTo = str_copy(strFrom, strTo);
~~~~~ ^
How should I correct in this way? Thanks!
The function returns a pointer to the terminating zero.
char *str_copy (const char *strFrom, char *strTo)
{
//...
*strTo = '\0';
return strTo;
}
Change it the following way
char *str_copy (const char *strFrom, char *strTo)
{
char *p = strTo;
while ( *p++ = *strFrom++ );
return strTo;
}
Also I would declare it the same way as standard C function strcpy is declared
char *str_copy( char *strTo, const char *strFrom );
As for your additional question then you may not assign a pointer or even other array to an array. So the compiler issues the error.
Arrays have no the assignment operator. You can only copy their elements.
Otherwise use standard class std::array.
After returning from str_copy you strTo does not point to the beginning of your copied string. In main strTo is ok, because it was passed by value (address of pointer after returning from str_copy is not changed even though you were using strTo++). But returned value of strFinal points to last character of copied string - '\0'.
For second part - char[10] has unchangeable addres, so you can't assign anything to variable of this type, like you tried in strTo = str_copy(...);.
Your second question : you are trying to assing char[10] with char* which is not possible
&strTo[0] = str_copy(strFrom, strTo);
But it's not usefull since the copy is done inside
In ur code, after calling str_copy() function:
char *strFinal = str_copy(strFrom, strTo);
strFinal points to the '\0', which is at the end of "abc123".
strTo in main() function can display correctly, because it is not THE SAME strTo
in str_copy() function, but points to strTo[10]. strTo in str_copy() still points to the terminating zero.