Well, I tried to find an answer to my question.
Basically, I have two string
variables, and I want to copy the first letters until to space, to another string
variable, but without success. I can't use strcpy()
.
#include <iostream>
#include <string>
using namespace std;
int main() {
string string1;
string string2;
cout << "String1:" << endl;
getline(cin, string1);
for (int i = 0; (i < string1.length()) && (string1[i] != ' '); i ){
string2[i] = string1[i];
}
cout << string2;
return 0;
}
CodePudding user response:
The variable string2
is defined to be empty, therefore string2[i]
is undefined.
Use string2.push_back(string1[i]);
CodePudding user response:
There is no need to reinvent the wheel. Just use standard C library:
auto pos = string1.find(' ');
string2 = (std::string::npos == pos) ? string1 : string1.substr(0, pos);
PS: Remy is right, you can use std::string::npos
as second argument in substr
. So it will be even simplier:
string2 = string1.substr(0, string1.find(' '));
CodePudding user response:
string2
is empty, so you can't copy from string1[i]
into string2[i]
.
You can append to the string like this though:
string2 = string1[i];
but with insuccess. I can't use the strcpy.
No need. std::string
has a copy assignment operator and a substr
member function so to copy the part of the string before the first space:
std::string string2;
auto pos = string1.find(' ');
if(pos != std::string::npos) { // space found
string2 = string1.substr(0, pos); // copy the substring [0, pos)
} else {
string2 = string1; // copy te whole string
}
If pos
returns npos
you can use that to copy the whole string, so you could strip the if
/else
above:
std::string string2;
auto pos = string1.find(' ');
string2 = string1.substr(0, pos);
So your loop is not needed.
You could construct string2
directly from the find
too:
std::string string2(string1, 0, string1.find(' '));