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>
Related
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[])
{
int i=0;
string s1 = "";
s1[i++]='F';
s1[i++]='U';
s1[i++]='A';
s1[i++]='A';
s1[i++]='D';
cout << s1;
return 0;
}
You're trying to modify elements in an empty string.
If you want your code to work there are several ways to do this:
add elements to s1, you can use s1 += 'A' or s1.push_back('A') instead.
Allocate enough space to modify each element by doing s1.resize(5) after string s1 = "";.
And possibly more, but that should get you started. Think of std::string as an array of characters. If your array is empty, you either have to resize it or add things to it.
Note: Don't use #include <bits/stdc++.h> just do #include <string>.
Note: Avoid using using namespace std;
s1 is empty, any indexing into it will be out of bounds and lead to undefined behavior. Do e.g. s1 += 'F' instead. – Some programmer dude
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);
}
Is this correct or is there a better way to do this.
Visual Studio gives an error saying 'strcpy() is depreciated'.
using namespace std;
char* ptr;
ptr=(char *)calloc(1,sizeof(char));
cout << "Input the equation." << endl;
string eqn;
getline(cin, eqn);
ptr = (char *)realloc(ptr, top + eqn.size()+1);
strcpy(ptr, eqn.c_str());
P.S. I want to ptr to be the exact size of the input equation.
Assuming that what you're trying to achieve is to create a modifiable char buffer given a std::string, the better choice is to use std::vector<char> to create such a buffer.
#include <vector>
#include <string>
#include <iostream>
//...
void foo(char *x)
{
// do something to 'x'
}
using namespace std;
int main()
{
cout << "Input the equation." << endl;
string eqn;
getline(cin, eqn);
// construct vector with string
std::vector<char> ptr(eqn.begin(), eqn.end());
// add null terminator
ptr.push_back(0);
foo( &ptr[0] );
}
The above creates a modifiable, null-terminated C-string by utilizing the std::vector called ptr. Note that there are no calls to malloc, calloc, etc.
strcpy is deprecated because it's a common source of buffer overflow problems, that are generally fixed with strncpy. Having said that, you are much better off using std::string in the first place.
If you want to have a duplicate of a string with malloc, you may simply use strdup:
char* ptr = strdup(eqn.c_str());
// ..
free(ptr);
My compiler is Code::Blocks. I am trying to eliminate vocals from a character sequence.
#include <iostream>
#include <cstring>
using namespace std;
char sir[256];
int i=0;
int main (){
cout<<"sir=";cin.getline(sir,256);
for (i=strlen(sir);i>0;i--){
if (strstr(sir[i],'aeiou')==0){
strcpy(sir+i,sir+i+1);
break;}}
cout<<"sir="<<sir<<"\n";
return 0;
}
I receive the following error:
error: call of overloaded 'strstr(char&, int)' is ambiguous
note: candidates are:
note: char* strstr(char*, cost char*) near match
But I think the problem is on strstr command...
'aeiou' is not a string literal in c/c++ use "aeiou".
In c/c++ string literal are represented inside " "(double quotes)
Read more here
So, apparently, the idea is to remove vowels. As others have said, use "aeiou" and not 'aeiou'. But you also need to use the right function to check whether you have a vowel. That's strchr(const char* s, int c), not strstr. strchr looks for an occurrence of c in the string that s points to, and returns a pointer to that occurrence, or, if it's not found, a pointer to the terminating nil character. So the test in the original code should be:
if (*strchr("aeiou", sir[i] != '\0')
Personally, I'd write this a bit more succinctly:
if (*strchr("aeiou", sir[i]))
As I wrote in the first comment, the expression
strstr(sir[i],'aeiou')
is wrong for two reasons: ' is for single characters, " is for strings, but the main reason is, that strstr finds the occurance of the whole thing, not of the characters separately.
Try this:
#include <iostream>
#include <cstring>
using namespace std;
char sir[256];
char sir2[256];
int i=0;
int main (){
cout<<"sir=";cin.getline(sir,256);
char* reader = sir;
char* writer = sir2;
while(*reader) {
if(*reader!='a' && *reader!='e' && *reader!='i' && *reader!='o' && *reader!='u') {
*writer = *reader;
++writer;
}
++reader;
}
*writer = '\0';
cout<<"sir="<<sir2<<"\n";
return 0;
}
ststr is defined by two function prototypes
const char* strstr( const char* str, const char* target );
char* strstr( char* str, const char* target );
your call is calling as
strstr(sir[i],'aeiou')
the first arg is a char type, not a char * type, so the compiler does know how to map that to const char * or char *
Also check your loop index as
i=strlen(sir)
will over index the char array and
i > 0
will NOT access the last character.
I'm trying to create a file whose name is a string constant, but a string consisting of a constant string "List" an integer + + an extension. Here's my code:
#include <iostream>
#include <vector>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main (){
int cont=0;
std::string result;
std::string name = "Lista";
std::string ext = ".txt";
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", cont);
result = name + numstr+ext;
freopen (result, "w", stdout);
cout<<result<<endl;
return 0;
}
When I try to build tells me the following error:
error: cannot convert std::string' toconst char*' for argument 1'
toFILE* freopen(const char*, const char*, FILE*)'|
How I can solve this?
As the compiler error states there is no implicit conversion from std::string to char const* (ie. a c-style-string in this context).
Though std::string has a member-function named c_str which will generate a null-terminated string and return a pointer to it that is very usable when dealing with legacy C functions.
Examples and notes
freopen (result.c_str (), "w", stdout);
char const * p = result.c_str ();
Please note that the c-style-string pointed towards by std::string::c_str will be invalidated if you make any modifications to the hosting object (in this case result), therefore it is normally not wise to store the value returned in a non-temporary variable.
You can read more about the function if you follow the link below:
cppreference.com - std::basic_string::c_str
i have a small app that does this exactly. there are several ways to do this.. the simplest of which is
const char * newvar = stringname.c_str();
If you're going to use sprintf, it's probably easiest to skip using std::string at all:
char name[32];
sprintf(name, "lista%d.txt", cont);
freopen(name, "w", stdout);
If you're going to use std::string (probably preferable for most C++ anyway), you probably want to use std::stringstream to create the name:
std::ostringstream name;
name << "lista" << cont << ".txt";
freopen(name.str().c_str(), "w", stdout);
However, I'd tend to avoid freopen in general, and avoid using C-style streams (such as stout) in C++. It's generally better to write to an ostream. Answers to a previous question show how to connect cout to a different output file, if you truly need to.