Man Overboard

Alrite, thanks for coming to my rescue...
Im trying to return the length of a string, when a user inputs a name;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>

int main ()
{
    string name;
    
    cout<<"What is your name: ";
    cin>>name;
  std::string str (name);
  std::cout << "The size of str is " << str.length() << " characters.\n";
  
  system("pause");
  return 0;
}

but its not compiling, am I doing something wrong.......thanks


Last edited on
Just odd

Whatever happened to std::string on the first string you declare and cout and cin. just that typo and you good to go.
str.size() will do.

Also, you have a bunch of errors:

line 10 and 6.

I would also declar the global: using namespace std; after the preprocessor directives at the top... But, that's your perogative.

Here is a better way:

psuedo code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name = "";
    cout<< "Enter your name: ";
    cout.flush();
    cin>> name;
    cout<< endl<< endl;
    cout<< "The length of your name is "<< name.size()<< "."<< endl;
    return 0;
}
Last edited on
Thanks,
May your life be blessed abundantly,

just one more question....
when I type "Hello World" the length comes back as '5' is there a way to handle spaces, or are they counted as part of a character...
Last edited on
you can use getline().

prototype:

getline(istream&, string&);

Example:

1
2
3
cout<< "Enter your name: ";
cout.flush();
getline(cin, name);


you can also use this for file streams:

1
2
3
4
5
string line = "";
ifstream in;
getline(in, line);
in.close();
cout<< "The first line of the file is \""<< line<< "\""<< endl;
Topic archived. No new replies allowed.