Solved

atoi question

Posted on 2013-05-24
10
326 Views
Last Modified: 2013-07-07
Hi
I am using atoi function in the the code and want to handle tis particular error case.
any garbage input to atoi will result in 0 getting returned which is a success code.

Is there a function i can use that returns an error code for garbage in case, or throw an exception.
I can use STL probably not use boost, but still would like to know what the options are with
either.

thanks
0
Comment
Question by:Vlearns
10 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 39195201
A 'plain' C-style alternative would be 'strtol()', which will not only point you to conversion errors, but also to where they occurred, e.g.

int read_int() {

  string s;
  int n = 0;
  char* pCnvEnd;

  while(1) {
    cin >> s;
    n = strtol(s.c_str(),&pCnvEnd,10);
    if (*pCnvEnd != NULL) { // invalid chars in string, not an integer
      cout << "Not a valid number, please re-enter the value" << " ";
    } else {
      break; //valid, stop loop
    }
  }

  return n;
}

Open in new window


Or you could use a std::stringstream like

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

int read_int() {

  string s;
  int n = 0;

  while(1) {
    cin >> s;
    stringstream ss(s);

    ss >> n;

    if (ss.fail()) { // invalid chars in string, not an integer
      cout << "Not a valid number, please re-enter the value" << " ";
    } else {
      break; //valid, stop loop
    }
  }

  return n;
}

Open in new window

0
 

Author Comment

by:Vlearns
ID: 39195240
Thanks for the responses.
here is the exact problem i am trying to solve

here is the string

response = (int)atoi(responsestring.c_str());

The responsestring is suppossed to be numerical codes like
1111
1222
3333
except in one case

where it is 4444\r\nurl=<redirect URL>.

this is what my code does

response = (int)atoi(responsestring.c_str());
idx = responsestring.find("url=");
                 if (response == User::ERR && idx != string::npos)
                 {
                     custom_error = "Please verify  " + responsestring.substr(idx + strlen("url="));
                 }
0
 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 39195258
In this case, 'strtol()' might help in two ways, e.g.

char* pCnvEnd;

response = (int)strtol(responsestring.c_str(),&pCnvEnd,10); // will return '4444'
idx = responsestring.find("url=");
                 if (response == User::ERR && pCnvEnd != NULL)
                 {
                     custom_error = "Please verify  " + responsestring.substr(pCnvEnd + strlen("\r\nurl="));
                 } 

Open in new window

0
 

Author Comment

by:Vlearns
ID: 39195285
what happens if we get garbage?
0
 

Author Comment

by:Vlearns
ID: 39195298
more specifically

what is the difference between 4444\r\nurl=<redirect URL>.

and 2222hellogarbage

garbage22222
0garbage8888
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 86

Expert Comment

by:jkr
ID: 39195299
You mean *only* garbage as input? That condition could be detected like

response = (int)strtol(responsestring.c_str(),&pCnvEnd,10);
if (responsestring.c_str() == pCnvEnd) {

  // nothing numeric at all
}

Open in new window

0
 
LVL 32

Expert Comment

by:phoffric
ID: 39195300
.
0
 
LVL 86

Expert Comment

by:jkr
ID: 39195319
2222hellogarbage - results in 2222 being returned and pCnvEnd pointing to hellogarbage  (offset 4 to string start)

garbage22222 - results in 0 being returned and pCnvEnd pointing to garbage  (offset 0 to string start)

0garbage8888 - results in 0 being returned and pCnvEnd pointing to garbage (offset 1 to string start)
0
 
LVL 33

Expert Comment

by:sarabande
ID: 39198554
if the string always (and trustable) begins with a number, atoi is sufficient. it would stop converting digits at the fist non-digit (periods and minus excluded). the strtol is necessary if you want refuse bad user-input.

Sara
0
 
LVL 84

Expert Comment

by:ozo
ID: 39198562
what do you want to do with
4444\r\nurl=<redirect URL>.
?
what do you want to do with
2222hellogarbage
or
garbage22222
or
0garbage8888
or whatever else you consider to be garbage?
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
returning a dereferenced pts in C++ 10 141
List out all word 7 257
Find Visual Studio Tools 2 92
Installshield for Embarcadero EX 10.1 Berlin 4 18
Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now