Fairly new to C++ here. I am trying to figure out if I can optimize my code by not calling the same function multiple times. For example see below:
funcCall is a standalone function so it cannot be removed, all it needs to know is those three paramters..
const char *a = "H";
const char *b = "e";
const char *c = "l";
const char *d = "l";
const char *e = "o";
const char *f = "Hi";
funcCall(f,a,b);
funcCall(f,c,d);
funcCall(f,d,e);
void funcCall(const char *one, const char *two, const char *three)
{
//Kindly ignore the syntax
//open the file and write the first two parameters to it
fopen(three.txt);
fwrite(one,two,three.txt); //ignore syntax
fclose(three.txt);
}
You can make an array of the characters, and loop over it two at a time, like so:
char abcdef[] = "Helllo";
const char* hi = "Hi";
for (char* p = abcdef; p < abcdef + 6; p += 2) {
funcCall(hi, p[0], p[1]);
}
This differs from your example in that it passes characters as the second and third arguments to funcCall, rather than null-terminated character strings.
After your edit, it looks like the parameters are really supposed to be strings, not just characters, so you'd want to have an array of strings rather than an array of characters. So you can do something like
std::vector<const char*> args = {"One", "Two", "Three"};
std::vector<const char*> files = {"A.txt", "B.txt", "C.dat"};
const char* hi = "Hi";
for (int i = 0; i < std::min(args.size(), files.size()); ++i) {
funcCall(hi, args[i], files[i]);
}
where funcCall takes const char* arguments as in your example. (It would probably be better to use std::string.)
Related
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();
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
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
i have
cost char* a="test_r.txt"
i want to strip the _r and add _n instead of it so that it becomes "test_n.txt"
and save it in const char* b;
what is the easiest way to do it ?
You can't directly modify the contents of a, so you'll need some copying:
std::string aux = a;
aux[5] = 'n';
const char* b = aux.c_str();
Like mentioned before, if you put your const char * into a std::string, you can change your characters. Regarding the replacing of a constant that is longer than one character you can use the find method of std::string:
const char *a = "test_r_or_anything_without_r.txt";
std::string a_copy(a);
std::string searching("_r");
std::string replacing("_n");
size_t pos_r = 0;
while (std::string::npos != (pos_r = a_copy.find(searching, pos_r)))
{
a_copy.replace(a_copy.begin() + pos_r,
a_copy.begin() + pos_r + searching.length(),
replacing.begin(), replacing.end());
}
const char *b = a_copy.c_str();
I have a c library which use char arrays as strings and i want to use c++ std::string on my code,
could someone help me how can i convert between char * c style strings and STL library strings ?
for example i have :
char *p="abcdef";
string p1;
and
string x="abc";
char *x1;
how can i convert p to p1 and x to x1
Use string's assignment operator to populate it from a char *:
p1 = p;
Use string's c_str() method to return a const char *:
x1 = x.c_str();
From char* to std::string :
char p[7] = "abcdef";
std::string s = p;
From std::string to char* :
std::string s("abcdef");
const char* p = s.c_str();
You can construct a std::string from a C string thus:
string p1 = p;
You can get a const char * from a std::string thus:
const char *x1 = x.c_str();
If you want a char *, you'll need to create a copy of the string:
char *x1 = new char[x.size()+1];
strcpy(x1, x.c_str());
...
delete [] x1;
string has a constructor and an assignment operator that take a char const* as an argument, so:
string p1(p);
or
string p1;
p1 = p;
Should work. The other way around, you can get a char const* (not a char*) from a string using its c_str() method. That is
char const* x1 = x.c_str();
#include <string.h>
#include <stdio.h>
// Removes character pointed to by "pch"
// from whatever string contains it.
void delchr(char* pch)
{
if (pch)
{
for (; *pch; pch++)
*pch = *(pch+1);
}
}
void main()
{
// Original string
char* msg = "Hello world!";
// Get pointer to the blank character in the message
char* pch = strchr(msg, ' ');
// Delete the blank from the message
delchr(pch);
// Print whatever's left: "Helloworld!"
printf("%s\n", msg);
}