I have been following various tutorials around the internet, getting a basic grasp of c++ and how it works.
I have written this code, which is me practicing the use of strcat and strlen.
When I first wrote the code, I wanted it to tell you the length of your first name, your last name and then your full name. However, because I used strcat every time I used strlen on "fullname" it would give me the number of letters plus an extra letter due to the space (" ") between the names being counted as another character.
So my original idea was to use ( strlen (fullname) - 1 ).
For some reason though, this was counted as an additional character, rather than taking it off.
So rather than being 12 letters (including the space) minus one making it 11. The total would come out as 13.
But when I use ( strlen (fullname) + 1 ) it then takes 1 off, making the strlen total 11.
Can anyone explain this to me? I'm utterly confused and sorry for the bad explanation, I hope you can understand what I'm trying to say.
Thank you!
TLDR; When I use (strlen (fullname) - 1) it adds a number to the total and when I use (strlen (fullname) + 1) it takes a character off the total. Why is this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char name[50];
char lastname[50];
char fullname[100];
cout<<"What is your first name?\n";
cin.getline (name,50);
cout<<""<< name <<" is "<< strlen (name) <<" letters long.\n";
cout<<"What is your last name?\n";
cin.getline (lastname, 50);
if ( strcmp ( lastname, "Boop" ) == 0 )
cout<<"We have the same last name!\n";
else
cout<<"We don't have the same last name.\n";
fullname[0] = '\0';
strcat (fullname, name);
strcat (fullname, " ");
strcat (fullname, lastname);
cout<<"So your full name is "<< fullname <<"!\n";
cout<<""<< name <<" is "<< strlen (name) <<" letters long, "<< lastname <<" is "<< strlen (lastname) <<" letters long.\n";
cout<<"That means that your full name has "<< strlen (fullname + 1) <<" letters in it!\n";
cin.get();
}
|