1

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.

4
  • Your TryEverything is size_t, does size_t have member size and length? Commented Apr 8, 2014 at 3:47
  • There aren't any deque in your code either. Commented Apr 8, 2014 at 3:53
  • This is a simplified version of what im working on. The debugger threw up that error the second it got to line bar = TryEverything.size() so I thought I must be assigning something wrong. It might be a completely different part of my code thats broken. Commented Apr 8, 2014 at 3:55
  • How does bar = foo.size(); "not work" (besides probably giving you a warning about a narrowing conversion?) Commented Apr 8, 2014 at 5:20

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.