getting the size of string

Jun 10, 2010 at 5:07am
this is my second day learning C++ so i dunno exactly what im doin,

i wnated to create a program that lets you enter a name and if the name youve entered is too long from the given requirments its loops and ask you to enter a name again,

here is my fuckin dumbass code

#include <iostream>

using namespace std;

int main()
{
//somvariables
int lenght = 5;
string name;

//program
cout <<"please enter your name: ";
cin >> name;


//tring to make a loop if the entered name to over the size of
//lenght varible
while (sizeof(name) > lenght)
{
cout <<"name is too long, please enter again: ";
}

//finally meets requirments
cout <<"Welcome, "
<< name;

return 0;
}

i know youd laugh at this but i really want to learn... hahahhahahah
Jun 10, 2010 at 5:40am
There are a few things wrong with your script. For example, when you say while (sizeof > length) it will loop forever.
I didn't have enough time to fix it, I'll have another look at it when I get back home.

gotta run!
Jun 10, 2010 at 8:39am
You have to ask the name in a loop repeatedly until the user inputs a name whose length is less than 5. In your code you're just processing the input once before the loop.

You can check the length of the string by calling either size() or length() on the string object. sizeof() returns the size of the string object (which is something entirely different); you want the string's length:

name.length()
Jun 10, 2010 at 9:09am

ReFix it. Remeber to call a function of a class is name.sizeof() or name.length(), because is c++

#include <iostream>

using namespace std;

int main()
{
//somvariables
int lenght = 5;
string name;

//program
cout <<"please enter your name: ";
cin >> name;


//tring to make a loop if the entered name to over the size of
//lenght varible
while (name.length() > lenght)
{
cout <<"name is too long, please enter again: ";
cout <<"please enter your name: ";
cin >> name;
}

//finally meets requirments
cout <<"Welcome, "
<< name;

return 0;
}
Last edited on Jun 10, 2010 at 10:51am
Jun 10, 2010 at 9:42am
jecaestevez: your code doesn't even compile because sizeof() is a compile time operator that returns size of object in bytes ( http://www.cplusplus.com/doc/tutorial/operators/ ).
So change
while (name.sizeof() > lenght)
into
while (name..length() > lenght)
Last edited on Jun 10, 2010 at 9:44am
Jun 11, 2010 at 7:12am
thank you guys!, ill refix it when i get home, @Null yes i've search the web and sizeof() returns the length of the variable bytes not the amount of characters in a string which im tryin to get as length,

and.. is length() a built- in function? what does it do?
Jun 11, 2010 at 7:45am
return number of elements
Jun 11, 2010 at 8:37am
thanks jecaestez, ive tried length() and it seems dont work if you dont #include<string>
Topic archived. No new replies allowed.