user3331346
user3331346

Reputation: 167

How do I store the size of a string in a variable

I am trying to gather and store user metadata for a project, but I can not find a way to store the length (number of characters) of a string.

int main()
{
 string foo;
 int bar;
 size_t TryEverything;

 cout << "Enter some random text: ";
 getline(cin, foo);

 bar = foo.size(); //Does not work
 bar = foo.length(); //Does not work
 bar = TryEverything.size(); //Does not work
 bar = TryEverything.length(); //Does not work

}

I want bar to equal the numbers of characters (including whitespace) the user enters. Any suggestions?

I am currently using visual studio 08, and the debugger throws this error:

"Expression: deque iterator not dereferencable."

Edit:

The error was coming from somewhere else in the code. Foo should actually work.

Upvotes: 1

Views: 201

Answers (2)

herohuyongtao
herohuyongtao

Reputation: 50717

In your code, TryEverything is of type size_t, it has no methods like size() or length().

Use

size_t sz = foo.size();

or

size_t sz = foo.length();

See it live: http://ideone.com/mHjvob.

Upvotes: 1

sidrakesh
sidrakesh

Reputation: 234

Try this, it worked for me:

#include<iostream>
#include<string>

using namespace std;

int main()
{
    string foo;
    size_t bar;

    cout << "Enter some random text: ";
    getline(cin, foo);

    bar = foo.size(); //Did work

    cout << bar;
}

Upvotes: 2

Related Questions