I am building a fast copy application using xcopy. I want to pass two variable source and destination to system(); I am trying like this
char *source = "D:\\SOFTWARE\\Internet";
char *destination = " D:\\test /s /e /d /y";
system("xcopy "+source+destination);
But it doesnt work. It work fine in java. same code. Thanks.
Rewriting Mike's code to eliminate all the issues we tend to flag in code being reviewed!
#include <string>
#include <cstdlib>
using std::string;
int main()
{
const string str{ "dir" };
const string str2{ " /w" };
const string final_string = str + str2;
std::system(final_string.c_str());
}
Your problem in your original code is that operator+ doesn't work with C style strings, which are just char* or char[] and not objects. You are asking to add pointers together, which is not a sensible thing.
As Mike points out, turn your raw char array input into std::string objects as soon as you need to do stuff with it, and then + will work.
In this particular case, you only need to copy one of the character arrays into objects (see docs on operator+= form 3):
string s {"xcopy "};
s += source;
s += destination; // this works, as there is an optimized form of operator+ for this.
std::system(s.c_str()); // access a nul-terminated character array to make the system call.
One more way of string concatenation is use of std::ostringstream. Source and destination paths are quoted in the code bellow to be more safe:
#include <sstream>
int main() {
const char *source = "\"D:\\SOFTWARE\\Internet\"";
const char *destination = " \"D:\\test\" /s /e /d /y";
std::ostringstream cmd;
cmd << "xcopy " << source << destination;
system(cmd.str().c_str());
}
Compile and run
You need to use std::string (from string header). Also, you need to go from string to a const char pointer.
#define _CRT_SECURE_NO_DEPRECATE
#include <cstdlib>
#include <string>
int main()
{
using namespace std;
string str{ "dir" };
string str2{ " /w" };
string final_string = str + str2;
char* cstr = new char[final_string.size() + 1];
strcpy(cstr, final_string.c_str());
system(cstr);
}
Related
Using the strcpy_s() function I want to collate the first three strings into the final one to print my full name. This is what I have and it doesn't work as I'm using char* strings and not std::strings.
#include <iostream>
using namespace std;
int main()
{
char str_first[] = "Nerf_";
char str_middle[] = " Herder";
char str_last[] = "42";
char str_fullName[35];
strcpy_s(str_fullName, (str_first + str_middle + str_last).c_str());
cout << str_fullName;
}
Any suggestions?
This should be close to what you're looking for, strictly using strcpy_s to concatenate strings together:
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
char str_first[] = "Nerf_";
char str_middle[] = " Herder";
char str_last[] = "42";
char str_fullName[35];
int index = strcpy_s(str_fullName, sizeof str_fullName, str_first);
index += strcpy_s(str_fullName + index, sizeof str_fullName - index, str_middle);
index += strcpy_s(str_fullName + index, sizeof str_fullName - index, str_last);
cout << str_fullName;
}
The index variable serves a couple of purposes: (1) to provide a new index into the output str_fullName string as the string is built, and (2) subtracted from sizeof str_fullName, it "adjusts" the available buffer size as the string is built.
Caveats are that you should add overflow checking via the output from strcpy_s, and (as noted by others) there are better patterns to follow for doing this, but probably as an academic exercise there's something good to be learned here.
You need to use both strcat and strcpy
See code comments for more info.
// disable SDL warnings in Visual studio
#define _CRT_SECURE_NO_WARNINGS
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
// TODO: insert checking code,
// to make sure destination can hold all characters + one termination.
char str_first[] = "Nerf_";
char str_middle[] = " Herder";
char str_last[] = "42";
char str_fullName[35];
// copy first string because we need null terminated destination
strcpy(str_fullName, str_first);
// append the rest, string is auto null terminated.
strcat(str_fullName, str_middle);
strcat(str_fullName, str_last);
cout << str_fullName;
}
If I am not mistaken the function strcpy_s expects three arguments. So either supply one more argument to the function call or use instead the function strcpy.
And there is no need to use the standard class std::string to perform the task.
The code can look the following way
strcpy( str_fullName, str_first );
strcat( str_fullName, str_middle );
strcat( str_fullName, str_last );
Or you could use strcpy_s and strcat_s provided that you will specify the correct number of arguments.
Pay attention to that you need to include the header
#include <cstring>
I am practicing some work with cstring and string.
Going from string to cstring using c_str() I get an incompatible data type compile error.
For example this is the code that gives said error:
string str = "StackOverFlow";
char inCstring[20]{};
inCstring = str.c_str();
Any ideas?
The problem is that str.c_str() returns a const char*, and you are trying to pass it to a char*. Use strcpy to get your expected result:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
string str = "StackOverFlow";
char inCstring[20];
strcpy(inCstring, str.c_str());
cout << "str: " << str << endl;
cout << "inCstring: " << inCstring << endl;
return 0;
}
So I have figured out two ways to accomplish this.
First, it is important to remember that you can't assign to a whole array, meaning it is necessary to specify the element of the array to assign to. Attempting to assign a string to char array simply will not work for this reason. That being said, by specifying the element it would be possible to assign a character in a specific element of a char array. Below are two methods that accomplish a string to cstring(string to char array) "conversion". Please see answer by Vincent for complete code. I have found Method B better since I would like to have max size on my character array.
Method A:
string str = "StackOverFlow";
const char* inCstring;
inCstring = str.c_str();
Method B:
string str = "StackOverFlow";
char inCstring[20]{};
Then use strcpy
strcpy(inCstring, str.c_str());
I am trying to copy 5 characters from a character array into a std::string
char name[] = "Sally Magee";
std::string first;
copy(name, name + 5, first.begin()); //from #include <algorithm>
std::cout << first.c_str();
However I get the string plus a whole bunch of unprintable characters that I do not want. Any ideas? Thanks.
Just do
char name[] = "Sally Magee";
std::string first(name, name + 5);
std::cout << first << std::endl;
see std::string constructor link
What the std::copy algorithm does is to copy one source element after the other, and advance the destination iterator after each element.
This assumes that
either the size of the destination container has been set large enough to fit all the elements you copy,
or you use an iterator type that increases the size of the destination container each time you make an assignment to it.
Therefore, if you want to use the std::copy algorithm, there are two ways of solving this:
Resize the string before making the copies:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
char source[] = "hello world";
std::string dest;
dest.resize(5);
std::copy(source,source+5,begin(dest));
std::cout << dest << std::endl;
return 0;
}
Using a back-insert iterator instead of the standard one:
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
int main()
{
char source[] = "hello world";
std::string dest;
std::copy(source,source+5,std::back_inserter(dest));
std::cout << dest << std::endl;
return 0;
}
However, as pointed out by others, if the goal is simply to copy the first 5 characters into the string at initialization time, using the appropriate constructor is clearly the best option:
std::string dest(source,source+5);
I'm new to C++ programming (haven't done it in 10+ since college.) and I'm trying to write a very basic program to grab a file name that has been passed as an argument. I'm just not getting how to get the file name. I'm using VS2012 Exp for Desktop.
Below is my code.
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <xstring>
#include <string>
//using namespace openutils;
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
wcout << "customconsole app has "<< argc <<" arguments passed. second one is: " << argv[1];
ofstream me_attach_file;
wstring newfilename = argv[1] && ".newext";
me_attach_file.open (".mailexpress");
me_attach_file << "Writing this to a file.\n";
me_attach_file.close();
return 0;
}
Replace this
wstring newfilename = argv[1] && ".newext";
with
wstring newfilename = argv[1];
newfilename += L".newext";
Some languages use & for string concatenation. C++ does not. In fact, there is NO operator that concatenates string literals and character pointers: + as string concatenation is defined by string objects and works only with them.
In addition, string literals have to be prefixed with L to use wide characters and be compatible with wstring.
&& doesn't add two strings together. The + operator does.
Also, C++ decides which of the many operator + functions to use by the type of the left-hand argument. You have two different types here, a _TCHAR string, a string literal ("this is a string literal") which is type char*, and you want to put it into a wstring.
First, a _TCHAR and char* aren't the same type, so it should be L".newext".
Second, you can't add two char*s, because that is adding two pointers, and pointer arithmatic does something different than what you want. So the first argument needs to be coverted to a wstring before you start adding things together.
Either:
wstring myStr = argv[1];
myStr += L".newext"
Or:
wstring myStr = wstring(argv[1]) + L".newext" + L"Additional stuff"
in the line
me_attach_file.open (".mailexpress");
you should pass the filename to the object.
me_attach_file.open (newfilename);
in your version, ofstream will open a file named ".mailexpress" without prefix (which is hidden on unix systems).
When I create something like
char* t = new char[44];
t = strcpy(s,t);
then strlen(t); return some wrong results. how I can change this?
Both strcpy and strlen expect to find the special character NUL or '\0' in the array. An uninitialized array, as the one you've created, may contain anything at all, which means the behavior of your program is undefined when it is passed to strcpy as the source argument.
Assuming the goal was to copy s into t, to make the program behave as expected, try this:
#include <iostream>
#include <cstring>
int main()
{
const char* s = "test string";
char* t = new char[44];
// std::strcpy(t, s); // t is the destination, s is the source!
std::strncpy(t, s, 44); // you know the size of the target, use it
std::cout << "length of the C-string in t is " << std::strlen(t) << '\n';
delete[] t;
}
But keep in mind that in C++, strings are handled as objects of type std::string.
#include <iostream>
#include <string>
int main()
{
const std::string s = "test string";
std::string t = s;
std::cout << "length of the string in t is " << t.size() << '\n';
}
What are you trying to do? Do you want to copy from s to t? If so, the arguments to strcpy are reversed.
char* t = new char[44]; // allocate a buffer
strcpy(t,s); // populate it
Such C-style string processing is a red flag, but that's all I can say given this little information.
This code might be helpful:
char * strcpy (char * destination, const char * source);
t = strcpy(t, s);
You have to initialize the variable t
Do something like this:
char *t = new char[44];
memset(t, 0, 44);
// strlen(t) = 0
The strcpy function is described thus:
#include <string.h>
char *strcpy(char *dest, const char *src);
The strcpy() function copies the string pointed to by src (including the terminating '\0' character) to the array pointed to by dest.
So, if you are trying to fill in your newly allocated array, you should be doing:
strcpy(t, s);
Not the other way around.