int main() {
string getEmail;
string email, firstName, lastName;
char dot = '.';
cout << "What is your email?" << endl;
getline(cin, email);
double pos = email.find(dot);
firstName = //store every letter before the dot;
cout << firstName << endl;
return 0;
}
how can I read the email, let's say I encounter '.', I want to read the word before it. e.i, Yes.no, I find '.' and read yes and store it in a variable.
CodePudding user response:
Why is pos
a double
? Positions are integers. For positions in strings there is a special integer type called size_t
, so your code should be
size_t pos = email.find(dot);
To get the first part of the email address you can use the substr
method. It has two parameters, a position (where the substring starts) and a count (how many characters in the substring). So to get the first part of the string you say
firstName = email.substr(0, pos);
Note that if email
does not contain a dot then this code will put the whole string into firstName
. If you want to test for that then you do it like this
size_t pos = email.find(dot);
if (pos == string::npos) // if no dot
cout << "no dot in email address";
CodePudding user response:
The substr()
should be the solution to this, but seems like the datatype of pos
is not necessary to be a double
, should be an integer.
int main()
{
string getEmail;
string email, firstName, lastName;
char dot = '.';
cout << "What is your email?" << endl;
getline(cin, email);
size_t pos = email.find(dot);
firstName = email.substr(0, pos);
cout << firstName << endl;
return 0;
}
CodePudding user response:
You could get the string from the start to the dot.
Lets suppose i
is the position of the dot. You could just return [0:i]
and it will get every character until the dot.