Creating a string with char[] - c++

#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!)

Related

Pulling a single char from a string and converting it to int

I am trying to pull a specific char from a string and convert it to an int. I have tried the following code, but I am unclear why it doesn't work nor can I find a way to do the conversion.
int value = 0;
std::string s = "#/5";
value = std::atoi(s[2]); // want value == 5
You can create std::string from one char and use std::stoi to convert to integer.
#include <iostream>
#include <string.h>
using namespace std;
int main() {
int value = 0;
string s = "#/5";
value = stoi(string(1, s[2])); //conversion
cout << value;
}
You can write:
std::string s = "#/5";
std::string substring = s.substr(2, 1);
int value = std::stoi(substring);
Using the substr method of std::string to pull out the substring that you want to parse as an integer, and then using stoi (which takes a std::string) instead of atoi (which takes a const char *).
You should read the manual page for atoi() more carefully. The actual prototype is:
int atoi(const char *string)
You are attempting to pass a single character rather than a pointer to a character array. In other words, by using s[2] you are dereferencing the pointer. You could, instead, use:
value = std::atoi(s+2);
or alternatively:
value = std::atoi(&s[2]);
This code doesn't dereference the pointer.
The argument to std::atoi must be char*, but s[2] is char. You need to use its address. And to get a valid C string from a std::string, you need to use the c_str() method.
value = std::atoi(&(s.c_str()[2]));
You should have gotten an error saying that the argument wasn't of the correct type.

How to put a string inside a char* variable in 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

how to define an array of chars in c++

I have this code and it's compiling correctly :
char classfname[512] = "classifiers/cabmodel_VOC05motorbikes.xml";
strcpy(classfname,argv[i]);
but when I tried to define an array contains strings from the same size of the above size
and with your all help it didn't work !
std::vector<std::string> classfname = {
"classifiers/cabmodel_VOC05motorbikes.xml",
"classifiers/cabmodel_interm_nst100_VOC06person01train5_orienthistmod.xml" ,
"classifiers/cabmodel_interm_nst40_VOC06cat01train5_trainval_orienthistmod_nopert_facereg.xml",
"classifiers/cabmodel_interm_nst100_VOC06bicycle01train5_trainval_orienthistmod.xml",
"classifiers/cabmodel_VOC06carside.xml",
"classifiers/cabmodel_interm_nst100_VOC06horse01train5_trainval_orienthistmod_randsel0100.xml"
};
char *classfname[6]={-----}
std::vector<std::string> classfname;
classfname.push_back(",,,");
with the function strcpy(classfname,argv[i]);
I got the error:
Error 2 error C2664: 'strcpy' : cannot convert parameter 1 from 'std::string' to 'char *
Converting string literals to a char* is no longer allowed, since it was never safe. Instead, make an array of const char*. (Although I'm not 100% positive this is the cause of your error, but your code doesn't match your error well, I think you changed something to put it on SO). std::string has a constructor from const char*, so this should work fine.
Also, it's good to note that (const::std string & is not right, so we know you changed stuff when you posted it here. Don't do that, or we can't help you much at all. It should be (const std::string&.
Also, MrC64 notes that you should use RAII instead of raw arrays and pointers. It's easier to use, and harder to mess up.
std::vector<std::string> classfname = {
"classifiers/cabmodel_VOC05motorbikes.xml",
"classifiers/cabmodel_interm_nst100_VOC06person01train5_orienthistmod.xml" ,
"classifiers/cabmodel_interm_nst40_VOC06cat01train5_trainval_orienthistmod_nopert_facereg.xml",
"classifiers/cabmodel_interm_nst100_VOC06bicycle01train5_trainval_orienthistmod.xml",
"classifiers/cabmodel_VOC06carside.xml",
"classifiers/cabmodel_interm_nst100_VOC06horse01train5_trainval_orienthistmod_randsel0100.xml"
};
If your compiler can't handle that syntax yet (many can't), use the code that Mr_C64 suggested.
[EDIT] You have changed your question dramatically to be a completely different question. Generally this is bad, because anyone who comes to this page looking for answers will see that our answers don't match your question anymore. If you have additional questions, you should use the search feature, or make a new question page.
Now your code has a std::vector of std::strings. Treat a std::string like you would an int. Just copy it, or pass it around with no worries. You don't have do use a special function to copy a int, so you don't need a special function to copy a string. Just do std::string newstring = classfname[0]; to get a copy of the string at index 0 in the array classfname.
Your "old" code makes an array of chars initialized to a string literal, and over-rights it with the input from argv[i] The best way to do that code is:
std::string classfname = "classifiers/cabmodel_VOC05motorbikes.xml";
classfname = argv[i];
If you just want to make an array of each of the arguments, that's easy:
int main() {int argc, const char** argv) {
std::vector<std::string> classfname(argv, argv+argc);
One solution is to use const char* like this:
const char *classfname[7]={"classifiers/cabmodel_VOC05motorbikes.xml",
"classifiers/cabmodel_interm_nst100_VOC06person01train5_orienthistmod.xml" ,
"classifiers/cabmodel_interm_nst40_VOC06cat01train5_trainval_orienthistmod_nopert_facereg.xml",
"classifiers/cabmodel_interm_nst100_VOC06bicycle01train5_trainval_orienthistmod.xml",
"classifiers/cabmodel_VOC06carside.xml",
"classifiers/cabmodel_interm_nst100_VOC06horse01train5_trainval_orienthistmod_randsel0100.xml",
};
Also if you want to have a std::vector containing these strings use can initialize it with the following statement:
const std::vector<std::string> classfname_vector(classfname, classfname + 7);
One more thing I noticed is that you declared an array with 7 elements but initialized it only with 6 string literals.
I'd just use std::vector<std::string> instead of a "raw" C array:
#include <string>
#include <vector>
std::vector<std::string> classfname;
classfname.push_back("classifiers/cabmodel_VOC05motorbikes.xml");
classfname.push_back("classifiers/cabmodel_interm_nst100_VOC06person01train5_orienthistmod.xml");
...
std::vector overloads operator[], so your call xmlloadmodel(classfname[i],model); should work.

Dynamic Structure in C++

struct testing
{
char lastname[20];
};
testing *pt = new testing;
pt->lastname = "McLove";
and I got
56 C:\Users\Daniel\Documents\Untitled2.cpp incompatible types in
assignment of 'const char[7]' to 'char[20]'
Why ?
Thanks in advance.
Because compile time arrays are constant. In your struct testing, you have an array of 20 chars, and you're trying to assign a pointer ("McLove", a compile time string, e.g., a const char*) to an array (a char[]), which won't work.
To copy the data "McLove" into the array, you need to use strncpy:
strncpy(pt->lastname, "McLove", 20); // 20 is the size of the array, change it when your array size changes, or better yet, use a constant for both
Or better yet, use std::string:
struct testing {
string lastname;
};
testing* pt = new testing;
pt->lastname = "McLove";
And now that will work, because std::string has an operator= that works with const char*.
As a side note, don't needlessly allocate objects on the free store (using new); allocate them on the stack:
testing pt; // not: testing* pt = new testing;
testing.lastname = "McLove"; // with std::string
The type of a string literal is pointer to const char. You can use that to initialize an array of char, but you can't assign to an array of char (from that or anything else).
Since you're apparently doing C++, you probably want:
struct testing {
std::string lastname;
};
testing pt;
pt.lastname = "McLove";
Allocating an object like testing dynamically is fairly unusual.
You can't assign one array to another. You're going to need to use strcpy (or better, strncpy).
Because string literals in C++ have the type const char[N] where N is the length of the literal, including the NULL character. So you're trying to assign a const char[7] to a array of type char[20], exactly what the compiler told you. Since arrays are not assignable this is invalid.
Use strcpy instead
strcpy( p-lastname, "McLove" );
Of course, you should also check if the destination is large enough to hold the source, or use some variant of strcpy that does this.

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.