Archived

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

caffeineaddict

Help with input

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
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