How to put a string inside a char* variable in c++ - c++

well I'm going to be brief here.
I have this variable:
char* String;
and a function:
void AddString(char str[])
{
}
And I need to add the str to String at the end of it for example:
if String = "ABC"
and str = "123"
after the function AddString String = "ABC123"
I searched all over the web, but I couldn't find what I need, any help?

In C++, use std::string rather than C-style character arrays:
#include <string>
std::string String;
void AddString(std::string str) {
String += str;
}
If you really want to do that by steam, then you'll need to allocate a large enough array for the result, copy the strings in, and remember to put a terminator (zero-valued character) after the end. C library functions like strlen, strcpy and strcat might be useful. The details are left as an exercise, since the question is about C++ not C.

For using C strings you have functions inside the cstring header file. To concatenate strings you have strcat

use strcat to combine the two char*
strcat takes two parameters, the destination char array c1 and the source char array c2.
You need to be sure that c1 is big enough to hold all the char from c1 and c2.
However you could use c++ strings. and the + operator will handle this for you.
string s1, s2;
string s3 = s1+s2

char* String;
void AddString(char str[])
{
strcat(String , str);
}
/*Also, make sure you have allocated space for String before using AddString*/
String = malloc(25*sizeof(char)); //25 just an example.
Also, since this is tagged for C++
You should be using std::string instead as shown in other answers

Related

String dimension error whel dealing with new operator

I'm trying to make something similar to the strlen(str,str) function (I have a return string) to learn using pointers and the new operator, here is my code:
char* strcat(char str1[], char str2[]){
int len=strlen(str1)+strlen(str2);
char* sfin = new char[len];
int i=0;
for (i=0;i<strlen(str1);i++)
*(sfin+i)=*(str1+i); //this could be *(sfin+i)= str1[i]
for (int j=0;j<strlen(str2);j++)
*(sfin+j+i)=*(str2+j); //this could be *(sfin+i+j)= str2[j]
return sfin;
}
It works, except for the thing that the new operator allocates too much memory (or is it right?), as seen from variables watcher:
P.S. in the main() function I retrieve str1 and str2 using gets(char*) and put them using puts(char*). len has the right content (9).
Results can be various: sometimes it puts the correct string and sometimes only two "strange" characters, depending on parametres.
Null-terminated strings need to be, well, null-terminted. You only copy all the characters up to the null-terminator but not the null-terminator itself. That is, if a program looks at the content of you string, it will continue looking until it finds a null-terminator. Make sure you add a null-terminator and also make sure the memory is deleted, e.g., using
std::unique_ptr<char[]> strcat(char const* str1, char const* str2) {
// ...
std::unique_ptr<char[]> ptr(new char[len]);
// ...
return ptr;
}
BTW, your use of strlen() in each iteration of the loop is likely to result in rather bad performance, especially if you have long strings.
In c and c++, strings have to be null terminated. The resulting string contains the values of string1 and string2 but it is not null terminated. The resulting string's length should be equal to strlen(strin1)+strlen(string2)+1 and the plus 1 char can be assigned the null terminator '\0'

What is the use of the c_str() function?

I understand c_str converts a string, that may or may not be null-terminated, to a null-terminated string.
Is this true? Can you give some examples?
c_str returns a const char* that points to a null-terminated string (i.e., a C-style string). It is useful when you want to pass the "contents"¹ of an std::string to a function that expects to work with a C-style string.
For example, consider this code:
std::string string("Hello, World!");
std::size_t pos1 = string.find_first_of('w');
std::size_t pos2 = static_cast<std::size_t>(std::strchr(string.c_str(), 'w') - string.c_str());
if (pos1 == pos2) {
std::printf("Both ways give the same result.\n");
}
See it in action.
Notes:
¹ This is not entirely true because an std::string (unlike a C string) can contain the \0 character. If it does, the code that receives the return value of c_str() will be fooled into thinking that the string is shorter than it really is, since it will interpret \0 as the end of the string.
In C++, you define your strings as
std::string MyString;
instead of
char MyString[20];.
While writing C++ code, you encounter some C functions which require C string as parameter.
Like below:
void IAmACFunction(int abc, float bcd, const char * cstring);
Now there is a problem. You are working with C++ and you are using std::string string variables. But this C function is asking for a C string. How do you convert your std::string to a standard C string?
Like this:
std::string MyString;
// ...
MyString = "Hello world!";
// ...
IAmACFunction(5, 2.45f, MyString.c_str());
This is what c_str() is for.
Note that, for std::wstring strings, c_str() returns a const w_char *.
Most old C++ and C functions, when dealing with strings, use const char*.
With STL and std::string, string.c_str() is introduced to be able to convert from std::string to const char*.
That means that if you promise not to change the buffer, you'll be able to use read-only string contents. PROMISE = const char*
In C/C++ programming there are two types of strings: the C strings and the standard strings. With the <string> header, we can use the standard strings. On the other hand, the C strings are just an array of normal chars. So, in order to convert a standard string to a C string, we use the c_str() function.
For example
// A string to a C-style string conversion //
const char *cstr1 = str1.c_str();
cout<<"Operation: *cstr1 = str1.c_str()"<<endl;
cout<<"The C-style string c_str1 is: "<<cstr1<<endl;
cout<<"\nOperation: strlen(cstr1)"<<endl;
cout<<"The length of C-style string str1 = "<<strlen(cstr1)<<endl;
And the output will be,
Operation: *cstr1 = str1.c_str()
The C-style string c_str1 is: Testing the c_str
Operation: strlen(cstr1)
The length of C-style string str1 = 17
c_str() converts a C++ string into a C-style string which is essentially a null terminated array of bytes. You use it when you want to pass a C++ string into a function that expects a C-style string (e.g., a lot of the Win32 API, POSIX style functions, etc.).
It's used to make std::string interoperable with C code that requires a null terminated char*.
You will use this when you encode/decode some string object you transfer between two programs.
Let’s say you use Base64 to encode some array in Python, and then you want to decode that into C++. Once you have the string you decode from Base64-decoded in C++. In order to get it back to an array of float, all you need to do here is:
float arr[1024];
memcpy(arr, ur_string.c_str(), sizeof(float) * 1024);
This is pretty common use, I suppose.
const char* c_str() const;
It returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C string), representing the current value of the string object.
This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null - character ('\0') at the end.
std::string str = "hello";
std::cout << str; // hello
printf("%s", str); // ,²/☺
printf("%s", str.c_str()); // hello

How to convert a char* pointer into a C++ string?

I have a C++ string. I need to pass this string to a function accepting a char* parameter (for example - strchr()).
a) How do I get that pointer?
b) Is there some function equivalent to strschr() that works for C++ strings?
To get the C string equivalent of
the C++ string object use c_str
function.
To locate the first occurence of a
char in a string object use
find_first_of function.
Example:
string s = "abc";
// call to strlen expects char *
cout<<strlen(s.c_str()); // prints 3
// on failure find_first_of return string::npos
if(s.find_first_of('a') != string::npos)
cout<<s<<" has an a"<<endl;
else
cout<<s<<" has no a"<<endl;
Note: I gave the strlen just an example of a function that takes char*.
Surprisingly, std:;string has far, far more capabilities than C-style strings. You probably want the find_first_of() method. In general, if you find yourself using the strxxx() functions on C++ std::strings, you are almost certainly doing something wrong.
Like much of the C++ Standard Library, the string class is a complex beast. To make the most of it, you really need a good reference book. I recommend The C++ Standard Library, by Nicolai Josuttis.
You can't get a char* from a string
string does not allow you free access to its internal buffer.
The closest you can get is a const char* using .c_str() if you want it null terminated or .data() if it doesn't have to be null terminated.
You can then cast the pointer returned by these functions to char* but you do this on your own risk. That being said this is a relatively safe cast to make as long as you make sure you're not changing the string. If you changed it then the pointer you got from c_str() may no longer be valid.
This code:
string str("Hello World!");
char* sp = (char*)str.c_str();
sp[5] = 'K';
is probably ok
However this:
string str("Hello World!");
char* sp = (char*)str.c_str();
str = "Chaged string";
sp[5] = 'K';
is most definitely not ok.
If you just want to assign a string literal to pw, you can do it like
char *pw = "Hello world";
If you have a C++ std::string object, the value of which you want to assign to pw, you can do it like
char *pw = some_string.c_str()
However, the value that pw points to will only be valid for the life time of some_string.
More here :
How to assign a string to char *pw in c++
GoodLUCK!!
std::string yourString("just an example");
char* charPtr = new char[yourString.size()+1];
strcpy(charPtr, yourString.c_str());
If str in your string use str.c_str() method to get the char* inside it.
Perhaps this exmaple will help you
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str ("Replace the vowels in this sentence by asterisks.");
size_t found;
found=str.find_first_of("aeiou");
while (found!=string::npos)
{
str[found]='*';
found=str.find_first_of("aeiou",found+1);
}
cout << str << endl;
return 0;
}
The C++ Standard provides two member functions of claass std::basic_string that return pointer to the first element of the string. They are c_str() and data(). But the both return const char *, So you may not use them with a function that has parameter of type char *.
As for function strchr then its first parameter is const char *. So you may use c_str() and data() with this function. However it is much better to use member function find()of class sttd::basic_string instead of strchr.

How do I append a string to a char?

How do I append a string to a char?
strcat(TotalRam,str);
is what i got but it does not support strings
std::String has a function called c_str(), that gives you a constant pointer to the internal c string, you can use that with c functions. (but make a copy first)
Use + on strings:
std::string newstring = std::string(TotalRam) + str;
If you want it as a char[] instead, you need to allocated memory on the heap or stack first. After that, strcat or sprintf are possible options.
You can't append a string to a char, you can only append a string to a string (or a char* if using the C string functions). In your example, you'll have to copy (the char) TotalRam into a string of some sort, either a C++ std::string, or make a char[2] to hold it and the required terminating NULL character. Then you can either use the C++ string with C++ functions or the char[2] with strcat and friends.
for performance, do this:
char ministring[2] = {0,0};
// use ministring[0] as your char, fill it in however you like
strcat(ministring,str);
The char array is stack-allocated so it is extremely fast, and the second char with the value of zero acts as a string terminator so that functions like strcat will treat it as a 'c' string.

How to assign a string to char *pw in c++

How to assign a string to a char* (char pointer) in C++?
char *pw = some string
For constant initialization you can simply use
const char *pw = "mypassword";
if the string is stored in a variable, and you need to make a copy of the string then you can use strcpy() function
char *pw = new char(strlen(myvariable) + 1);
strcpy(pw, myvariable);
// use of pw
delete [] pw; // do not forget to free allocated memory
If you just want to assign a string literal to pw, you can do it like char *pw = "Hello world";.
If you have a C++ std::string object, the value of which you want to assign to pw, you can do it like char *pw = some_string.c_str(). However, the value that pw points to will only be valid for the life time of some_string.
If you mean a std::string, you can get a pointer to a C-style string from it, by calling c_str. But the pointer needs to be const.
const char *pw = astr.c_str();
If pw points to a buffer you've previously allocated, you might instead want to copy the contents of a string into that buffer:
astr.copy(pw, lengthOfBuffer);
If you're starting with a string literal, it's already a pointer:
const char *pw = "Hello, world".
Notice the const again - string literals should not be modified, as they are compiled into your program.
But you'll have a better time generally if you use std::string everywhere:
std::string astr("Hello, world");
By the way, you need to include the right header:
#include <string>
I think you may want to do this:
using namespace std;
string someString;
geline(cin,someString);
char *pw = strdup(someString.c_str());
But consider doing it another way. Check out http://tiswww.case.edu/php/chet/readline/rltop.html (GNU Readline library). I don't know details about it, just heard about it. Others may have more detailed or other tips for reading passwords from standard input.
If you only want to use it for a single call for something you do not need to copy the contents of someString, you may use someString.c_str() directly if it is required as const char *.
You have to use free on pw some time later,
String must be enclosed in double quotes like :
char *pStr = "stackoverflow";
It will store this string literal in the read only memory of the program.
And later on modification to it may cause UB.