Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

caffeineaddict

Help with input

This topic is 6246 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How can you count the number of characters entered into a variable... example int x; cin>>x; how can i count how many characters are in the variable i guess is what i''m asking.

Share this post


Link to post
Share on other sites
Advertisement
You can''t really count them if you are using an int value. An int value is a (normally) 32-bit value and is going to be the same size no matter what. All you can do is look at the value.

If you read your input into a string that would be a different story. You could do:

cin >> mystring;

int numchars = strlen( mystring );

lol but to be honest I never really learned about the stream operators in C++ so I don''t know that cin >> mystring is really a valid operation. Sorry if not. lol

Seeya
Krip

Share this post


Link to post
Share on other sites
You could create a string of the integer, and then count the number of characters in the string:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
int x;
cout << "x: ";
if (cin >> x)
{
ostringstream s;
s << x;
string::size_type num_len = s.str().size();
cout << num_len;
}
else
{
cerr << "Please input a number!\n";
}
return 0;
}


HTH



Free multiplatform ANSI C++ Standard Library implementation
Visual C++ STL fixes
Visual C++ 6.0 noncompliance issues
C++ FAQ Lite

Edited by - JungleJim on June 9, 2001 9:39:40 AM

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!