I need to put "hello world" in c.
How can I do this ?
string a = "hello ";
const char *b = "world";
const char *C;
string a = "hello ";
const char *b = "world";
a += b;
const char *C = a.c_str();
or without modifying a:
string a = "hello ";
const char *b = "world";
string c = a + b;
const char *C = c.c_str();
Little edit, to match amount of information given by 111111.
When you already have strings (or const char *s, but I recommend casting the latter to the former), you can just "sum" them up to form longer string. But, if you want to append something more than just string you already have, you can use stringstream and it's operator<<, which works exactly as cout's one, but doesn't print the text to standard output (i.e. console), but to it's internal buffer and you can use it's .str() method to get std::string from it.
std::string::c_str() function returns pointer to const char buffer (i.e. const char *) of string contained within it, that is null-terminated. You can then use it as any other const char * variable.
if you just need to concatenate then use the operator + and operator += functions
#include <string>
///...
std::string str="foo";
std::string str2=str+" bar";
str+="bar";
However if you have a lot of conacatenation to do then you can use a string stream
#include <sstream>
//...
std::string str1="hello";
std::stringstream ss;
ss << str1 << "foo" << ' ' << "bar" << 1234;
std::string str=ss.str();
EDIT: you can then pass the string to a C function taking a const char * with c_str().
my_c_func(str1.c_str());
and If the C func takes a non const char * or require ownership you can do the following
char *cp=std::malloc(str1.size()+1);
std::copy(str1.begin(), str2.end(), cp);
cp[str1.size()]='\0';
Related
I just started learning c++, andI have problems with uderstanding working on adresses and rewriting variables from one adress to another.
I have a program to correct:
using namespace std;
void cp(char* str2, char* str1) {
cout << &(str1+1);
}
int main()
{
char *str1 = "ppC";
char str2[10] = "Witaj";
// cout << str2 << endl; // Witaj
cp(str2,str1);
}
Problem:
I have to write a function to rewrite text from str1 to str2.I also have to use specified amount of memory to store the text in str2.
But I've got stucked at first step:
I would like to begin with taking the adress of str1 (its adress of str1[0] am i right?) then i would like to go in loop fro after adding +1 to each adress to go through all elements of str1 and write it to new char* var and return it.
As I have understood you are going to write a function that copies a string stored in one character array in another character array.
Usuaaly such string functions also returns pointer to the first character of the destination array.
So instead of
void cp(char* str2, char* str1);
It is better to declare the function like
char * cp( char *str2, const char *str1 );
It is a low level function and t should not check whether there is enough space in the destination array. It is a problem of the caller.
So the function can be defined like
char * cp( char *str2, const char *str1 )
{
char *p = str2;
while ( *str2++ = *str1++ );
return p;
}
Take into account that the second parameter has type const char *. In this case you can use constant arrays as an argument for this parameter including string literals.
Using the variable declarations in your program you could call the function the following way
std::cout << cp( str2, str1 ) << std::endl;
I have a question about a char array:
I have a form '"1"+lapcounter+":"+seconds' that must come in a char array.
How can i fill this array in this form?
Thanks
If you mean you have some numeric variables which you want to format into a string, use a string-stream for that:
std::stringstream ss;
ss << "1" << lapcounter << ":" << seconds";
Now you can extract a string from that:
std::string s = ss.str();
and if you really want a character array for some reason (which I'm sure you don't)
char const * cs = s.c_str();
Use sprintf, or snprintf. This function works similar to printf but instead of standard output, the output will go to char array you specified. For example:
char buffer[32];
snprintf(buffer, sizeof(buffer), "1%d:%d", lapcounter, seconds);
to_string is used like this:
#include <iostream>
#include <string>
int main()
{
int lapcounter = 23;
std::string str("1");
str.append(std::to_string(lapcounter ));
str.append(":seconds");
std::cout << str << std::endl;
}
prints
123:seconds
if you really need a char array you get that from ss.c_str()
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am new to c++ and am looking for a way to concatenate three char* strings together ? Can anyone show me some sample code ?
Kind Regards,
In C++ you typically use std::string for strings. With that you can concatenate with the + operator. For instance:
std::string s = s1 + s2 + s3;
where s1, s2 and s3 are your three strings held in std::string variables.
If you have s1, s2 and s3 as char* or const char* then you write it a little differently.
std::string s = s1; // calls const char* constructor
s += s2; // calls operator+=() overload that accepts const char*
s += s3; // and again
If you really want to use null-terminated C strings, and C string functions, then you use strcpy to copy and strcat to concatenate.
char[SOME_LARGE_ENOUGH_VALUE] str;
strcpy(str, s1);
strcat(str, s2);
strcat(str, s3);
where s1, s2 and s3 are your three strings as char* or const char*.
Of course, choosing SOME_LARGE_ENOUGH_VALUE is the fun part. If this is a learning exercise, then you might like to learn how to allocate the string dynamically.
char *str = new char[strlen(s1) + strlen(s2) + strlen(s3) + 1];
Then you can use the strcpy, strcat shuffle above. But now you are responsible for destroying the raw memory that you allocated. So, think about how to do that in a robust way, and then use std::string!
From the comments, it seems you want to concatenate three strings, and then pass the resulting string to a low-level hash function that accepts a C string. So, I suggest that you do all your work with std::string. Only at the last minute, when you call the hash function, use the c_str() function to get a const char* representation of the concatenated string.
const char * foo = "foo";
const char * bar = "bar";
const char * baz = "baz";
One option:
std::string s = foo;
s += bar;
s += baz;
Another option:
std::stringstream ss;
ss << foo << bar << baz;
std::string s = ss.str();
Another option of last resort:
char* s = new char [strlen (foo) + strlen (bar) + strlen (baz) + 1];
s[0] = 0;
strcat (s, foo);
strcat (s, bar);
strcat (s, baz);
// ...
delete [] s;
std::string s1( "Hello " );
std::string s2( "C++ " );
std::string s3( "amateur" );
s1 += s2 + s3;
std::cout << s1 << std::endl;
Or
char s1[18] = "Hello ";
char s2[] = "C++ ";
char s3[] = "amateur";
std::strcat( std::strcat( s1, s2 ), s3 );
std::cout << s1 << std::endl;
A simple way to concatenate:
#include <iostream>
int main()
{
const char* a = "welcome ";
const char* b = "to C++ ";
const char* c = "world";
std::string d(a);
std::cout<< d.append(b).append(c);
return 0;
}
I am trying to convert my string into a const char that can be used with the strtok function. What am I doing wrong?
int _tmain(int argc, _TCHAR* argv[])
{
char * pointer_char;
int pos = 0;
std::string str = " Hello good sirtttttt..!.";
int i = 0;
int length = str.length();
const char * cstr = str.c_str();
cout << "Testing string is " << str << endl << endl;
pointer_char = strtok (str.c_str()," ,.;-!?##$%^&");
}
Do not use .c_str() result with strtok directly.
strtok needs char* not a constant and it tries to change the passed string. Since your passed string comes from a const char* then it's not possible to change it. If you try to cast it to a non-const type before passing it to this function then undefined behavior will be invoked.
You need to make a copy and then pass that copy to strtok, for example:
char *c = strdup(str.c_str()); // It's not standard but simple to write
pointer_char = strtok(c," ,.;-!?##$%^&");
free(c);
Try not to use strtok specially in C++ (you have many alternatives), it is not thread safe.
strtok doesn't take const char * as first parameter it takes a char*. The string has to be modifiable.
char *strtok (char *str, const char *delimiters);
str
C string to truncate.
Notice that this string is modified by being broken into smaller strings (tokens).
Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
This code keep saying : error: invalid initializer
char * ss = "hello world";
char s[10] = ss;
std::transform(s, s + std::strlen(s), s, static_cast<int(*)(int)>(std::toupper));
How can it be fixed?
Your initializer of the array with a C string is invalid. The good news is that you do not need it at all:
char * ss = "hello world";
char s[12];
std::transform(ss, ss + std::strlen(ss)+1, s, static_cast<int(*)(int)>(std::toupper));
cerr << s << endl;
Note that I padded your s array with an extra element for the terminating zero.
char s[10] = ss;
This tries to set an array's value equal to a pointer, which doesn't make any sense. Also, ten bytes isn't enough (there's a terminating zero byte on the end of a C-style string). Try:
char s[20];
strcpy(s, ss);
Your array assignment is illegal and, in the case of your code, isn't needed in the first place.
const char * ss = "hello world";
char s[12];
std::transform(ss, ss + std::strlen(ss)+1, s, static_cast<int(*)(int)>(std::toupper));
You can't assign a pointer to an array because you can't assign anything to arrays but initialiser lists. You need to copy the characters from ss to s. Also, an array of size 10 is too small to hold "hello world". Example:
char * ss = "hello world";
char s[12] = {}; // fill s with 0s
strncpy(s, ss, 11); // copy characters from ss to s
Alternatively, you could do
char s[] = "hello world"; // create an array on the stack, and fill it with
// "hello world". Note that we left out the size because
// the compiler can tell how big to make it
// this also lets us operate on the array instead of
// having to make a copy
std::transform(s, s + sizeof(s) - 1, s, static_cast<int(*)(int)>(std::toupper));