How do we have char str[700] initializing into C++ string syntax?
#include <string>
int main(){
//...
char str[700];
// string eqivalent...
string str; //...?
}
Thanks
It is ok to just assign values to string as it will allocate the memory using internal allocator for you. Or you can just use reserve() method to do that before hand:
See:
https://en.cppreference.com/w/cpp/string/basic_string/reserve
Or using the construtor to assign some defaults:
std::string str(700, '\0');
std::string has inbuilt constructor doing this work for us.
use it like
char *a;
//Processing on character array a
string str(a);
//str now a C++ string equal to a
Related
I am trying to append string literals to std::vector<char*> but whatever I try i can not append them.
std::vector<char*> vector1;
vector1.push_back("examplestring"); // gives warning C++11 does not allow conversion form string literal..
const char* anotherstring = "examplestring";
vector1.push_back(anotherstring); // gives error no matchcing member to call push_back
Can someone please correct me with the proper way of adding string to the vector?
Thanks in advance.
For starters in your code snippet there is no object of the type std::string. You code snippet deals with string literals.
String literals in C++ have types of constant character arrays.
So for example the string literal used in this call
vector1.push_back("examplestring");
can not be converted from the type const char[14] to the type char *.
If you are going to store in the vector only pointers to string literals then you should declare the vector like
std::vector<const char *> vector1;
Otherwise you need to dynamically allocate strings and push them on the vector. For example
#include <cstring>
#include <vector>
//...
std::vector<char *> vector1;
char *s = new char[ sizeof( "examplestring" )];
std::strcpy( s, "examplestring" );
vector1.push_back( s );
When the vector will not be needed any more you have to free the allocated memory for stored strings.
If you want to store objects of the type std::string nevertheless you have to create copies of the objects using dynamic memory allocation. Otherwise the lifetime of strings should be at least not less than the lifetime of the vector.
For example
std::vector<char *> vector1;
std::string str( "examplestring" );
char *s = new char[ str.size() + 1];
std::strcpy( s, str.c_str() );
vector1.push_back( s );
You can use const_cast to cast away const-ness for the sake of passing a const object where a non-const object is expected by an interface. Note, however, that this is just for bridging the interface; the function to which you pass the (casted) const-value (or any other part accessing the passed object) must not alter the object, though. This would yield undefined behaviour:
std::vector<char*> vector1;
const char* anotherstring = "examplestring";
char* anotherStringNonConst = const_cast<char*>(anotherstring);
vector1.push_back(anotherStringNonConst);
#include <cstdio>
//#include <string>
#include <vector>
int main() {
std::vector<const char*> vector1;
vector1.push_back("examplestring");
const char* anotherstring = "examplestring";
vector1.push_back(anotherstring);
for (auto* pCstring : vector1) {
printf("%s\n", pCstring);
}
return 0;
}
Using std::vector<const char*> works, but still suggest strongly to use std::vector<std::string> for memory safety.
How to append std::string to std::vector<char*>?
Example:
std::string example;
std::vector<char*> vector1;
vector1.push_back(example.data());
Note that you must be careful to keep example alive for at least as long as pointer is being used. And you mustn't modify the string in ways that would invalidate the pointer.
so I'm currently trying to read user input into a char array, but every single example I've looked at defines the size of the array upon its initialization. What I'm looking for, essentially, is a way to read user input (perhaps with getline, as I would want to read user input as a string) and store it in an array.
Let's say a user inputs this into the program:
This is a string
I would want the array size to be able to fit that string, and place the null terminator after the "g". Then, another user could put a string of any size that they so desired into the program, but I would basically want my program to always make the array size just enough to contain what was read in from input.
I haven't been able to get this working and it's been a couple of hours of browsing endless pages, so any help would be appreciated! Thanks.
As Tony Delroy said on his comment (I can't comment yet), you should be using std::string.
If you really need an char array, as parameter to a function for example, you can use the function c_str() to get the content of the std::string as a const char* array or if you need a char* array, you can copy the content of the array given by c_str() to a dynamically allocated array, using
char* cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());
As an addend, you need to include the header cstring in order to use the function strcpy and need to use delete[] cstr to delete the char* when you're not going to use it anymore
#include <iostream>
#include <cstring>
using namespace std;
// string argument as std::string
void foo(string str) {
// function body
}
// argument as const char*
void bar(const char* str) {
// function body
}
// argument as char*
void baz(char* str) {
// function body
}
int main() {
string str;
getline(cin, str);
foo(str);
bar(str.c_str());
char* cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());
baz(cstr);
delete[] cstr;
return 0;
}
you should use std::string for that.
the null terminator has no use in std::string, because you can just use:
string.size()
to get the size of the user input.
if want to traverse a string like a char array one by one it should look like something like this:
std::string input;
std::getline(std::cin, input);
for (int i = 0; i < input.size() ; i++)
{
std::cout << input[i];
}
I need to convert char array of C into string c++ but the char array is an element of struct.
Code:
This is my Structure in C
typedef struct myStruct
{
char name[50];
char abc[50];
ESL_BOOL status;
}MyStruct;
and I want to access name[50] in c++ but for that I have to convert it into string.
I have tried strcpy and memcpy.
I am using ESL_BOOL status; and it is working but confused with name[50].
The first thing you should change in the class name in your struct because that will likely cause problems because it is a keyword in C++.
Then for converting a C string into a C++ one, you can simply use the std::string constructor that accepts C-style strings.
std::string myCppString(MyStruct.name);
typedef struct myStruct {
char name[50];
char mclass[50];
ESL_BOOL status;
} MyStruct;
class is a reserved keyword of the C++ language. If you try to use it, tokenizer will take it as a keyword and cause problems later in the parsing phase, as an identifier will be expected.
It was once considered a good practice to precede all of the struct´s members with m or m_ to avoid such collisions.
To your problem: just the default "from C string" string (const char* s) constructor should be enough.
MyStruct obj;
std::string objsName(obj.name);
std::string objsClass(obj.mclass);
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
#include <iostream>
using namespace std;
int main()
{
char strin[206];
strin = "sds";
cout<<strin;
}
Why do I get this error?
error: incompatible types in assignment of 'const char [4]' to 'char [206]' //on line strin = "sds"
I am following this beginner tutorial
The error comes from the fact that you're trying to assign one array into another. The assignment operator can't do that; you'd have to copy the array using strcpy() or std::copy().
However, since you want to work in C++, you should really be using std::string instead of char[] to store strings.
You can not assign an array to another directly. It should be copied element to element.
Use std::strcpy from <cstring> header
char strin[206];
std::strcpy(strin, "sds");
Use std::string from <string> header
std::string strin;
strin = "sds";
Since you're using C++, choose second one.
Your code;
strin = "sds";
should be:
strcpy(strin, "sds");
C/C++ doesn't have string opertions built-in. You need to use either function:
strcpy(strin, "sds"); // will work in C and C++
// strncpy(strin, "sds", 205); // safer if you want to copy user-given string
or std::string:
std::string strin(206, 0);
strin = "sds"; // only C++
strin is a array which is a const pointer to chars, not a pointer to chars.
You tried to change the const pointer and this is forbidden
you need to copy the string. e.g. this way
strcpy (string, "sds");
(Aware buffer overflows in general cases!)