Char and string to numerical

I have been trying to accept negative numbers. i'm trying to use a char array to store user input... I stored user input into the char array. Then, i tried to check if they are numeric and not alphabetical. Then, if the user input is numerical, i then attempt to putback( parameters ) the character array. Then i get the input and store it into my integer object. I have also attempted to do a much more complex program with a similiar goal as to set my strings back to numbers if the string was infact numeric and i have been successful. Infact, i wouldn't have gone this far with a character array but there is one thing i have tried to fix with the strings that i could not seam to fix. What my problem was with that program was me trying to accept a NEGATIVE NUMBER... I would like to know how to solve this problem. So after that long and complicated note, i will sum it up because i don't expect everyone to read the whole thing because i tend to skip to the end of something and read the first and last sentences of a long paragraph because my brain would go into overload too lol



Program 1: ( using string to integers or doubles... Who cares... atof() atoi() you pick... )

Problems: isdigit( parameter ) will not accept negative numbers.

Oh, and i can easily just check for "exit"... Oh and i just worked on this and
apparently you can't use isdigit() on a string so that's probably another reason why i tried using a char array

Program 2: ( attempt at a solution )

Problems:

storing input in a char array and converting the input from the char array back into an integer
Last edited on
Don't bother duplicating code to parse the string to see if it [i]could[/b] be converted to a number -- just try to convert it.
That's too easy though. I'm doing this to learn. If i don't check if it's a number, i can't find whether my value is 0 because the user entered 0 or if 0 remained as the default because if a user error.. plus, i want to know if the user is typing something other than a digit.
That's too easy though. I'm doing this to learn.

I think there is a difference, though, between reinventing the wheel for academic purposes and not taking the simplest route.

Write yourself some code to convert the string to a number (for your learning purposes), and have some way to indicate whether it was successful or not. As Duoas said, don't go writing the same code to check if the string is convertible, then to prepare it for conversion.
Its important to note that when you're reading the characters into your integer the characters numerical value will be in ASCII so you have to convert it to a normal number by subtracting '0' from it or else you will be getting much higher numbers than you intended.
/** Ok.. Here is a great solution to what I have been trying to do for a month or so now!! :D **/


#include <iostream>
#include <string>

int userDigitInput( std::string mystring ) {

while( true ) {

int x = 0;

mystring = " ";

getline( std::cin, mystring );

for ( int i = 0;i<=mystring.length()-1;i++ ) {

if ( !isdigit( mystring[i] ) ) {

x++;

}

}

if ( x>0 ) {

std::cout << "\nThat is not a digit. Please try again";

}

else if ( x == 0 ) {

x = atoi( mystring.c_str() );

return x;

}

}

}

/***** Feel free to use this... It can be used by anyone. I'm so proud of this :) The only thing i have not yet tested for is if the number is to big or if it is zero which i will later add but I'll just leave the rest for anyone else to figure out! Happy coding! **/
That whole thing can be simplified to far fewer lines of code like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

int userDigitInput(std::string mystring) 
{	
	int x;
	if((atoi(mystring.c_str()) == 0) && mystring.compare("0") == 1)
	{
		std::cout << std::endl << "That is not a digit.  Please try again.";
		return 0;
	}
	else
	{
		x = atoi(mystring.c_str());
		return x;
	}
}
Last edited on
c_str() is a function.
What if the string is "0"?
Your function doesn't behave like Dabeast45's.
Woops. I edited it and added a second condition to not give the error if the user enters "0". As for the missing parentheses that was a mixture of alcohol and me being stupid :/
Last edited on
Ok, i have a pretty freaking awesome program that I've been working on for a while. Pretty good size header file. Its getting really good. Only problem is if the user is mean and decides to input nothing. i've tried multiple things...

!cin.get()
!getline( std::cin, mystring )
try {

getline( std::cin, mystring );

}

catch ( std::exception e ) {

}

std::string i = "a";
std::cin.putback( i );
( this just messes up the inputs ) ... Thinking of maybe skipping the first character which should work but that would require much much more work on my part..

Is there an easy way to check for no input? Oh and you can forget this attempt.. The one I'm about to show you might work but i want my entire input to be in the string... I want whitespaces to be included.

cin >> thisThing;
if ( !cin ) {

std::cout << "Please enter a digit...\n";

}


EDIT: Also, i have a function that's pretty neat in my header file. My header file that i created is very good for string and digit input. The function that i made and love is one that utilizes time and can output strings as if it were being typed. Its pretty awesome. I can show anyone the function or even the whole header file if you would happen to be interested.

EDIT: Also, i called the function helloNeo cuz it reminded me of the matrix lol
Last edited on
In the case of getline() and no input, wouldn't the string be empty?
Checking for an empty line is simple :D
1
2
3
4
if(!string[0])
{
// stuff goes here
}

Out of curiosity, what is this program doing?
Last edited on
That is why I always recommend getting all user input using getline(), since the user will always press ENTER when he is done giving input. Then use stringstreams or whatever to parse the user's input as correct or incorrect. This also gives you the ability to give nice default answers.

(Note that this is different than simply correcting or suggesting how to properly use a cin >> construct.)
Nope, i still get an error if its an empty string. I think its because...

getline( std::cin, mystring );

I think that already parses the string and because the user entered nothing, checking for no input still causes a run time exception. The error is... string subscript out of range... plus some other crap in there like where the error was at. So.. How do I fix this without a mean user messing my program up? Thanks for any help! :)

I'm using this program as a basis for all of my c++ knowledge. I hope to add a gui and many other things to it. I still have some things I need to add but this error is a really big programming problem.

EDIT: And, oh.. by the way.. This program calculates the users distance, current speed, or time to arrive at a destination. This program still has a longgggg way to go.

Edit: Oh, and i just realized that i didn't tell you that receiving no input causes an exception. But, that's the reason why I'm asking. I don't think checking for no input is going to help or not
Last edited on
How are you checking using the subscript notation? If the string is empty, naturally any checks to get a specific character will fail.
I'm positive that the if statement I posted above will always be executed if the user enters an empty line. Also you're using the "worse" version of getline. It's better to use the version with three parameters like this:
 
std::cin.getline(where to store data, maximum number of characters to store, delitiming character which should usually be set to '\n' which means when to stop when the user presses enter);
What are you talking about, 'worse'? std::getline() is for std::strings, and the istream method is for C-style strings. I say ditch C-strings and use the one in the std namespace and strings. If you are using std::strings, do this: mystring == "" or mystring.empty() to check for an empty string.
Last edited on
OK, you guys don't understand what the problem is. When i use getline( whatever );
its automatically going to screw up because getline() already parses my string.. If the user doesn't enter a string, there is absolutely nothing to parse and this causes a run time exception. How do I fix this?

EDIT: I'm thinking now, maybe use cin.get() and keep getting the characters until its the endoftheline() and when it is, break out of the loop and then insert() all the characters into the string

EDIT: Also, even if this did work, this would not compile because every string must have 1 character in it. You cannot test for this ....... mystring == "" ...................
Last edited on
If by "parse" you mean selecting everything the user types until he presses ENTER and storing it in a string, then yes, I suppose that is a screw up.

All user input is terminated by pressing ENTER. Your input must account for this.

If the user does not enter anything usable, that is easily detectable and you can simply skip to the next input attempt, with or without a message complaining to the user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
  {
  string s;
  cout << "Enter something> ";
  while (getline( cin, s ))
    {
    if (s.find_first_not_of( " \t\v\f" ) == string::npos)
      {
      cout << "Nothing is not something.\nEnter something> ";
      continue;
      }

    istringstream ss( s );
    double d;
    ss >> d;
    if (ss.eof())
      {
      cout << "Good job! You entered the number " << d << ".\n";
      }
    else
      {
      cout << "Good job! You entered the string \"" << s << "\".\n";
      }
    break;
    }
  return 0;
  }

Good luck now!
Thankyou so much Duoas! I could not find that on the internet to save my life! :D
Topic archived. No new replies allowed.