Solved

How to check if C++ string has junk values

Posted on 2010-09-22
14
525 Views
Last Modified: 2012-05-10
Hi,

I need to check if the string has wrong/junk values. How can I do it?

My string should have only integer values in them.

Example:
std::string s1="1234"      //This is a valid value
std::string s2="123a"      //This or any combination (including control characters) is not valid

I am using C++ (GNU compiler) and Linux.

thanks,
Sreeni
0
Comment
Question by:shykumar
  • 5
  • 3
  • 3
  • +2
14 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 168 total points
ID: 33736718
Try converting it to 'int' and see if that works, e.g.
#include <sstream>

std::string s2="123a";

int test;
std::stringstream ss(s2);

ss >> test;

if (ss.fail()) {

  // not only integer numbers
}

Open in new window

0
 
LVL 32

Assisted Solution

by:phoffric
phoffric earned 166 total points
ID: 33736836
const char * cstr = str.c_str(); // convert string to c-style string pointer    http://www.cplusplus.com/reference/string/string/c_str/   for(size_t i=0; i      if( !isdigit(cstr[i]) ) {http://www.cplusplus.com/reference/clibrary/cctype/isdigit/
0
 
LVL 32

Expert Comment

by:phoffric
ID: 33736976
re:
======================
std::string s2="123a";
int test;
std::stringstream ss(s2);
ss >> test;
======================
    This gives 123 since only valid chars making up an integer will be read in.
0
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 
LVL 32

Expert Comment

by:phoffric
ID: 33736986
But the next attempt to do a ss >> test should fail due to the 'a'.
0
 
LVL 40

Assisted Solution

by:evilrix
evilrix earned 166 total points
ID: 33737718
If you just want to filter out any arbitrary values or value just use the find_first_of or find_first_not_of method on the string.

http://www.cplusplus.com/reference/string/string/find_first_not_of/
http://www.cplusplus.com/reference/string/string/find_first_of/
0
 
LVL 31

Expert Comment

by:farzanj
ID: 33743174
Please try this:
try
{
     i1 = atoi (s1);   //try converting string to integer
}


It is up to you if you want to use just "catch" with it to display the error message or want to "throw" and then catch.  It is up to your design.

Another observation,

Just use namespace std, it makes life much easier and syntax beautiful.

So you can have
#include <iostream>
#include <string>

using namespace std;


int main()
{


}

.....

Hope it helps
0
 
LVL 40

Expert Comment

by:evilrix
ID: 33745959
>> It is up to you if you want to use just "catch" with it to display the error message or want to "throw" and then catch.  

atoi doesn't throw - it is a C function. Further, how will you distinguish 0 from non-numeric values that will also be reported as 0?
0
 
LVL 31

Expert Comment

by:farzanj
ID: 33746061
Ok.  Please disregard the try part.

I think the best way is to use "at" member function and testing each character to individually if it is between 0 and 9.  Make a small function IsNum, if you want to test it.  If you don't care to test, atoi should ignore trailing garbage.  So 1234abc should change to 1234.

if s is the string, atoi(s.c_str())
0
 
LVL 40

Expert Comment

by:evilrix
ID: 33746102
>> I think the best way is to use "at" member function and testing each character to individually if it is between 0 and 9.

What "at" member function?

Seriously, why reinvent the wheel? string already has two perfectly good functions to do this as I explained above! http:#33737718
0
 
LVL 31

Expert Comment

by:farzanj
ID: 33746346
I don't think I am reinventing the wheel.  May be I missed but I don't think there is a member function to test whether string is an integer.  The function atoi() removes any trailing garbage.

With "at" you can.  I know you can do it without "at".  It is just made for this purpose.

//Is number
bool success = true;
for(int i = 0; i < s.length(); i++)
{
    if( s.at(i) < 0 || s.at(i) > 9 )
    {
        success = false;
        break;
    }
}

//If success == false, it was not an integer.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 33747430
>> The function atoi() removes any trailing garbage.

The asker isn't asking to convert (which might be one reason to want to remove "trailing garbage") they are asking "How to check if C++ string has junk values" and you just cannot do this (properly) with atoi because it will always return you a number.

http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

Return Value

On success, the function returns the converted integral number as an int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.

So how does that tell you if it contains "junk"?

>> May be I missed but I don't think there is a member function to test whether string is an integer
http://www.cplusplus.com/reference/string/string/find_first_not_of/
Look at the example they provide. A modified version is below, which will solve the askers problem.


string s ("");
if ( s.find_first_not_of("0123456789") != string::npos )
{
    // contains a non-numeric value
}

Don't you agree that is a lot simpler than what you posted previously?

>> With "at" you can.
Sorry, just realised you were referring to the member function on string. Yes, you can use that to access the individual characters in the string - but you don't need to do this for solving this problem as string already has a member to do this.
0
 
LVL 1

Expert Comment

by:dkhoo
ID: 33795620
bool isNum(const char* p)
{
      istringstream s(p);
      double d;
      s >> d;
      return s && s.rdbuf()->in_avail() == 0;
}
0
 
LVL 40

Expert Comment

by:evilrix
ID: 34246443
This question has been classified as abandoned and is being closed as part of the Cleanup Program.  See my comment at the end of the question for more details.
0

Featured Post

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
SetCurrentDirectory path limit 7 122
Eclipse IDE - Cannot copy/paste from console output 8 193
Issues with C++ Class 19 92
Precision Problem in C++ 7 33
When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

810 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