I am trying to write something which takes user input (int) and doesn't cause an error if user inputs something other than an out of range int or an alpha. What I have actually works fine on my computer with XP but it causes errors on all 3 of my win98/ME computers. I have traced it down to the problem being with the use of char and casting but no idea exactly what the problem is or how to fix it. Below is an edited piece of my code. Also, maybe even a dumber question, but why can't I declare my variables outside main without error?

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
char *numb;
int number;

cout<<" Enter a number 1-10 ";
cin>>numb;
number=atoi(numb);

while((number<1)||(number>10)){
     cout<<"\n\n You must enter a number between 1 and 10 ";
     cin>>numb;
     number=atoi(numb);
     }
cout<<"\n Correct selection!";
cin.ignore();
cin.get();
return 0;
}

Recommended Answers

All 4 Replies

It shouldn't work on XP either.

You've declared "numb" as a pointer to characters, but there aren't actually any characters being pointed at.

Question: why are you using a char* anyway? Use the STL string class:

#include <iostream>
#include <string>
using namespace std;

int main()
{
  string s;
  int number;

  cout << "Enter a number in 1-10 ";
  cin >> s;
  ...
}

If you want to convert a string to a number, you should use the STL stringstream:

#include <sstream>
...
  stringstream ss;
...
  ss.str( s );
  while (!(ss >> number) || ((int)ss.tellg() != (int)s.length()))
  {
    cout << "Try again: ";
    cin >> s;
    ss.clear();
    ss.str( s );
  }
...

The second part of the condition protects against input like "42x". The stuff at the bottom of the loop resets the stringstream.

Hope this helps.

Well apparently dev c++ doesn't support stringstream or at least the version I have doesn't. Until I find an updated version I have to work around it. I was using char instead of string because I thought atoi only worked with char and I thought atoi was the way to go to insure that any keystroke other than a number would return 0 so I could use it in my while loop. Is that not correct? I'll play around some more until I hear back but it seemed like alpha input caused problems before using atoi and I could only get that to work by using char.

Both atoi() and strtoul() take char*, but the string class will give you a char* if you say: number = atoi( s.[B]c_str[/B]() ); (where s is a std::string).

You must have a really, really old version of DevC++. Why don't you go download the latest version? (Or at least update your STL)?

Hope this helps.

I just went ahead and upgraded my Dev C++/compiler and fixed the prob with stringstream. Thanks for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.