C++ Appending to an array - c++

const int fileLength = fileContent.length();
char test[1000];
for (int p = 0; p < fileLength; ++p){
test[p].append(fileContent[p]); // Error: expression must have class type
};
I'm attempting to append the characters of a text file into an array which i've created. Though I'm getting the error " expression must have class type ". Tried googling this error to no avail.

test is an array of char. test[p] is a char. char does not have any members. In particular, it does not have an append member.
You probably want to make test a std::vector<char>
const auto fileLength = fileContent.length();
std::vector<char> test;
for (const auto ch : fileContent)
{
test.push_back(ch);
}
or even:
std::vector<char> test( fileContent.begin(), fileContent.end() );
if you then really need to treat the test as an array (because you are interfacing to some C function for example), then use:
char* test_pointer = &*test.begin();
If you want to use it as a nul-terminated string, then you should probably use std::string instead, and get the pointer with test.c_str().

char array does not have any member function by the name append .However , std::string does have one member function named append like below :
string& append (const char* s, size_t n);
I think you by mistake have used char array instead of std::string .
std::string will resolve this problem like below :
const int fileLength = fileContent.length();
string test;
for (int p = 0; p < fileLength; ++p){
test.append(fileContent[p],1); // Error: expression must have class type
};
Better way would be string test(fileContent) .You can access test just like a array .Refer string class for more details .

Related

How to convert a double variable into a char array?

I'm working on a project for school, and we just found out that outtextxy() (a function from graphics.h, which we must use) requires as the text parameter a char array.
Here is its declaration: void outtextxy (int x, int y, char *textstring)
The issue is that we need to print out a number of type double, including the decimal point. I have previously tried making it work using knowledge from other similar questions, but none has worked.
Here are is my latest attempt, which resulted in a Segmentation Fault:
char *DoubleToString(long double x)
{
char s[256]="\000";
std::ostringstream strs;
strs << x;
string ss = strs.str();
for(int i=0; i < ss.length(); i++)
s[i] = ss[i];
return s;
}
NOTE: I am still somewhat new to programming and I don't exactly know what ostringstream and the bitshift-looking operation are doing, but I tried to copy-paste that part in hopes of it working.
... requires as the text parameter a char array.
Ok, then use a std::string:
std::string DoubleToString(long double x)
{
std::ostringstream strs;
strs << x;
return strs.str();
}
If you need the underlying character array use the strings data() method. It does return a pointer to the first element of the strings character array. For example:
std::string s = DoubleToString(3.141);
function_that_needs_pointer_to_char( s.data() );
Note that before C++17 data returned a const char* (and since C++11 the character array is null-terminated, as one would expect ;).
I know it is undefined behaviour, but it works. And I only need to pass the returned char* to outtextxy(), and not manipulate it later on, since I have the double variable stored in an object.
char *DoubleToString(long double x)
{
char s[256]="\000";
std::ostringstream strs;
strs << x;
string sd = strs.str();
strcpy(s, sd.data());
return s;
}

How to convert int and std::string to char*? [duplicate]

This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
Closed 8 years ago.
How to convert int and std::string to char* ?
I'm trying to do this :
int a = 1;
std::string b = "str";
char* x = a + b;
I don't want something like this:
std::stringstream ss;
std::string str2char;
ss << a;
str2char = ss.str() + "str";
std::vector<char> writable(str2char.size() + 1);
std::copy(str2char.begin(), str2char.end(), writable.begin());
x = &writable[0];
How to deal with this, please.
One way would be to use a string stream (include <sstream>), output data of various types into it, and then grab the output as a string or as a const char*, like this:
std::stringstream ss;
int a = 1;
std::string b = "str";
ss << a << b;
std::string res(ss.str());
const char *x = res.c_str();
Demo on ideone.
If you need to convert to char*, not to const char*, make a copy of c_str instead - replace the last line as follows:
char *x = new char[res.size()+1];
strcpy(x, res.c_str());
// Use x here, then...
delete[] x;
Finally, you can use vector instead of a string to get a writable pointer without the need to delete. Note that this approach does not let you return your char* from a function, because its data would be tied to the scope of the vector with its characters. Here is a demo of this approach.
If you are using C++11, std::to_string() is a good option:
int a = 1;
std::string b = "str";
std::string one = std::to_string(a);
std::string one_plus_b = (one + b);
const char * x = one_plus_b.c_str();
And as it was pointed out by other answers, 'x' can only be used inside the local scope.
int and std::string to char*?
Here are a couple one-liners:
char* p = strdup((std::to_string(a) + b).c_str());
...use p...
free(p);
...or, if your system provides it (I don't think it's in the C++ Standard itself)...
char* p = asprintf("%d%s", a, b.c_str());
...use p...
free(p);
Note that these are C library functions, and the memory allocation is malloc/realloc/free-family, which can not be mixed with new/delete (which means the pointer shouldn't be wrapped in a Standard smart pointer, though of course a free-specific or generic scope guard could be used).

Substitute char array with std::string in an input parameter to a function

Following are two legacy routines. I cannot change the routine declarations.
static bool GetString(char * str); //str is output parameter
static bool IsStringValid(const char * str); //str is input parameter
With call as follows
char inputString[1000];
GetString(inputString);
IsStringValid(inputString);
Instead of using fixed char array, I want to use std::string as the input. I am not able get the semantics right (string::c_str).
With IsEmpty it should not be a problem:
std::string str = "Some text here";
IsEmpty(str.c_str());
Though it's pretty useless if you have a std::string as then you would normally just call str.empty().
The other function though, that's harder. The reason is that it's argument is not const, and std::string doesn't allow you to modify the string using a pointer.
It can be solved, by writing a wrapper-function which takes a string reference, and have an internal array used for the actual GetString call, and uses that array to initialize the passed string reference.
Wrapper examples:
// Function which "creates" a string from scratch
void GetString(std::string& str)
{
char tempstr[4096];
GetString(tempstr);
str = tempstr;
}
// Function which modifies an existing string
void ModifyString(std::string& str)
{
const size_t length = str.size() + 1;
char* tempstr = new char[length];
std::copy_n(str.c_str(), tempstr, length);
ModifyString(tempstr);
str = tempstr;
delete[] tempstr;
}
You can't use c_str for the first function, because it returns a const char*. You can pass a std::string by reference and assign to it. As for is empty, you can call c_str on your string, but you'd be better of calling the member empty().
I think you can use the string container of STL ( Standard template Library ) .
#include <string>
bool isempty ( int x ) {
return ( x == 0 ) ? true : false ;
}
// inside main()
string s ;
cin >> s ; // or getline ( cin , s) ;
bool empty = isEmpty (s.length()) ;
std::string has c_str() which you can use for IsEmpty. There ist no function which gives you a non const pointer. Since std::string's allocation is not guaranteed to be contiguous you cannot do something like &s[0] either. The only thing you can do is to use a temporary char buffer as you do in your example.
std::string s;
char inputString[1000];
std::vector<char> v(1000);
GetString(inputString);
GetString(&v[0]);
s = &v[0];
IsEmpty(s.c_str());

C++ const char* To const char* const

I am currently writing an assignment for my class that is supposed to act as a very basic shell. I am nearly finished, but I am running into an issue with execvp and my character array of parameters. Here is a light snippet of my code.
//Split the left content args
istringstream iss(left);
while(getline(iss, s, ' ')){
v.push_back(s);
}
//Get the split string and put it into array
const char* cmd_left[v.size()+1];
for(unsigned int i = 0; i < v.size(); i++){
cmd_left[i] = v.at(i).c_str();
}
cmd_left[v.size()] = 0;
v.clear();
And this is utilized by...
execvp(cmd_left[0], cmd_left);
My error is
assign3.cxx:96:34: error: invalid conversion from ‘const char**’ to ‘char* const*’ [-fpermissive]
I understand that the problem is that my character array isn't full of constant data, so I need to essentially go from const char* to const char* const. I read something about const_cast, but I wasn't sure if that is what I need to be doing.
If you would be so kind, could you help me get my array of character arrays to be properly accepted by that function? If you need me to post more of my code, let me know.
Thanks
The problem is you cannot pass const variable to function expecting non-const argument.
other word, const char * is a subset of char *.
remove the const
/*const*/ char* cmd_left[v.size()+1];
add const_cast here
cmd_left[i] = const_cast<char *>( v.at(i).c_str() );
other parts of your code look suspicious, but this will make it compile
Without any const_cast:
istringstream iss(left);
while(getline(iss, s, ' ')){
v.push_back(s);
}
//assuming v is not empty! which you were already
string command = v[0]; //store the command in a separate variable (this makes a copy of the string)
char* cmd_left[v.size()+1]; //not a (const char)*
for(unsigned int i = 0; i < v.size(); i++){
cmd_left[i] = new char[v[i].size()+1];
strcpy(cmd_left[i], v[i].c_str()); //copy contents of each string onto a new buffer
}
cmd_left[v.size()] = NULL;
v.clear(); //if you really want to; not necessary from the code you posted
//...
execvp(command.c_str(), cmd_left);
It is not easy, sometimes not possible to create a const dynamic array of elements because all the elements have to declared within the initializer {}.
But luckily you could tell the compiler that the array you are passing is going to be const at least for the certain duration. You could do the following this would yield
&((char* const) (const_cast<char*>(cmd_left[0]) ))
The const_cast inside would remove the const-ness of the array of characters std::string is owning. So, it is quite possible that function might change the contents of array of characters behind the back of std::string. When behaviour of functions taking such argument is known then this might be ok.
If you want to create a const array of char* without resorting to const_cast or managing memory using new/delete, you could use std::vector > instead of vector of strings.
istringstream iss(left);
while(getline(iss, s, ' ')){
v.push_back(std::vector<char>(s.length()+1));
strcpy(&v.back().front(),s.c_str());
}
//Get the split string and put it into array
char* cmd_left[v.size()+1];
for(unsigned int i = 0; i < v.size(); i++){
cmd_left[i] = &v.at(i).front();
}
cmd_left[v.size()] = 0;
v.clear();
execvp(cmd_left[0], &((char* const)cmd_left[0]));
Hope this helps.

How to concat two const char*?

I am not able to concat two const char*.
I do the following:
const char* p = new char[strlen(metadata.getRoot())+strlen(metadata.getPath())];
strcat(const_cast<char*>(p),metadata.getRoot());
strcat(const_cast<char*>(p),metadata.getPath());
strcpy(const_cast<char*>(args2->fileOrFolderPath),p);
function(args2->fileOrFolderPath);
Now when I print the variable args2->fileOrFolderPath on the console then the correct output appears... But when I call a method with the variable as parameter, and work with the variable then I got a segmentation fault. What is the problem?
I did not declare them like this but i know they have this information
So, I have this:
const char* ruta1 = "C:\\Users\\Deivid\\Desktop\\";
const char* ruta2 = "lenaGris.xls";
Then I used this for concatenation:
char * RutaFinal = new char[strlen(ruta1) + strlen(ruta2) + 1];
strcpy(RutaFinal, ruta1);
strcat(RutaFinal, ruta2);
printf(RutaFinal);
This worked for me.
I would prefer using std::string for this, but if you like char* and the str... functions, at least initialize p before using strcat:
*p = 0;
BTW:
using std::string, this would be:
std::string p = std::string(metadata.getRoot()) + metadata.getPath();
strcpy(const_cast<char*>(args2->fileOrFolderPath), p.c_str());
function(args2->fileOrFolderPath);
And you don't have to deallocate p somewhere.
1.
const char* p=new char[strlen(metadata.getRoot())+strlen(metadata.getPath())+1];
the length plus 1 to store '\0'.
2.
strcpy(const_cast<char*>(args2->fileOrFolderPath),p);
You can not guarantee args2->fileOrFolderPath 's length is longger than strlen(p).
This works well
#include <iostream>
using namespace std;
void foo(const char*s){
cout<<s<<endl;
}
int main(int argc,char*argv[]){
const char* s1 = "hello ";
const char* s2 = "world!";
const char* p = new char [strlen(s1)+strlen(s2)+1];
const char* s = new char [strlen(s1)+strlen(s2)+1];
strcat(const_cast<char*>(p),s1);
strcat(const_cast<char*>(p),s2);
strcpy(const_cast<char*>(s),p);
cout<<s<<endl;
foo(s);
return 0;
}
You have char pointers, pointing to char constants which can't be modified . What you can do is to copy your const char array to some char array and do like this to concate const strings :
char result[MAX];
strcpy(result,some_char_array); // copy to result array
strcat(result,another_char_array); // concat to result array
I believe you need to include space for the null terminator, and the first parameter to strcat shouldn't be const as you're trying to modify the memory being pointed to.
You want to do something like this:
char * str1 = "Hello, ";
char * str2 = "World!\n";
char * buffer = malloc(strlen(str1) + strlen(str2) + 1);
strcpy(buffer, str1);
strcat(buffer, str2);
printf(buffer);
Which prints out "Hello, World!" as expected.
As for the error you're seeing when using a parameter, I've wrote some tests to see why it doesn't break when using a const local variable. While compiling using a const char * for the pointer I'm using as the target I get this warning:
./strings.c:10: warning: passing argument 1 of ‘strcat’ discards qualifiers from pointer target type
As it states, const is discarded and it works as expected. However, if I pass a parameter which is a const char * pointer, then I get a bus error when trying to modify the buffer it writes to. I suspect what is happening is that it ignores the const on the argument, but it can't then modify the buffer because it's defined as const elsewhere in the code.