   Trimming a char* in c++
  I'm using a char* in c++ as a string.  I want to find out if it can be converted to the number 0, and I need to trim it down.  However, I can't find a function to do this.  Is there a function or a generally accepted algorithm for this?Also, I'm looking for a way to determine if a string is equivalent to the floating value of 0.0 so that I can verify whether or not atof results equal to 0.0 are errors or the actual float value.  Is there any way to do this? (Will the value always have the same number of digits and so on?)   
  If you are using C++ you should be using std::string and not char*.  To translate between strings and floats look at either boost::lexical_cast or std::stringstreamEdit: Excellent - I have become one of Zahlman's minions :)[Edited by - chowe6685 on June 22, 2006 7:41:34 PM];  As mentioned above, really, the std::string is fairly well supported. Even the embedded Visual C++ 4.0 environment for Windows Mobile does.Below is the code I've whipped up for token processing, as desired -- see: bool is_real_number(const string &src_string)Converting to char* shouldn't be too difficult, but in my humble opinion is a waste of time unless you absolutely have to avoid std::string.string lower_string(const string &src_string){string temp = src_string;for(string::iterator i = temp.begin(); i != temp.end(); i++)*i = tolower(*i);return temp;}string upper_string(const string &src_string){string temp = src_string;for(string::iterator i = temp.begin(); i != temp.end(); i++)*i = toupper(*i);return temp;}string trim_whitespace_string(const string &src_string){string temp_string;for(size_t i = 0; i < src_string.length(); i++)if(!isspace(src_string))temp_string += src_string;return temp_string;}bool is_signed_int(const string &src_string){if(src_string == "" || src_string.size() > 5)return false;string temp = lower_string(src_string);for(size_t i = 0; i < temp.size(); i++){if(temp == '-' && i != 0)return false;if(!isdigit(temp) && temp != '-')return false;}return true;}bool is_long_unsigned_int(const string &src_string){if(src_string == "" || src_string.length() > 10)return false;string temp = lower_string(src_string);for(size_t i = 0; i < temp.size(); i++){if(!isdigit(temp))return false;}double num = atof(temp.c_str());if(num > 4294967295.0)return false;return true;}bool is_real_number(const string &src_string){//ie: //1//-23e4//1.E2//-2.717//.31415e1//-7.53e-9//7.53e+9if(src_string == "")return false;string temp = lower_string(src_string);bool found_dot = false;bool found_e = false;bool found_digit = false;for(size_t i = 0; i < temp.size(); i++){if(isdigit(temp)){if(found_digit == false)found_digit = true;}else if(temp == 'e'){if(found_e == true || found_digit == false || i == temp.size() - 1)return false;elsefound_e = true;}else if(temp == '-' || temp == '+'){if(!(i == 0 || temp[i-1] == 'e') || i == temp.size() - 1)return false;}else if(temp == '.'){if(found_dot == true || (i != 0 && temp[i-1] == 'e'))return false;elsefound_dot = true;}else{return false;}}return true;};  Agreed, if you're using char * in your code, you likely have a bug (stole someone elses sig).   ;  EDIT: I see my minions are hard at work, providing short introductory posts ahead of me ;DQuote:Original post by gamechampionxI'm using a char* in c++ as a string.That's your first mistake.Quote:I want to find out if it can be converted to the number 0, and I need to trim it down.Define "can be converted". Define "trim down".Quote:However, I can't find a function to do this.  Is there a function or a generally accepted algorithm for this?Well, a char* "string" (in quotes, because of following discussion) is understood by convention to end at the first char with a zero value (a so-called "null terminator"), so you could just write one to the appropriate position. However...Quote:Also, I'm looking for a way to determine if a string is equivalent to the floating value of 0.0 so that I can verify whether or not atof results equal to 0.0 are errors or the actual float value.  Is there any way to do this? (Will the value always have the same number of digits and so on?)Using atof() at all is your second mistake.In C++, we sidestep all of this by representing the string with std::string, and converting strings to numeric values by making use of std::stringstreams (or relying on a wrapper around this process, such as boost::lexical_cast). You actually don't even need to make use of std::strings (at least not explicitly) in order to use the std::stringstream to do your parsing. I'll show you a wrapper that expects a std::string, because you can pass a char* directly to such a function and it will be implicitly wrapped up as a std::string (the reverse does *not* happen; when you want to call a function that takes a char*, and you have a std::string, you need to "unwrap" it first with the .c_str() member function.)Here is one way to set up the std::stringstream for parsing. The function will read into an "out parameter" if possible, and leave the value untouched otherwise. The return value will indicate whether the read was possible. You'll also notice that the function is templated - so you'll be able to use the same function with any data type that supports streaming operations (i.e. you could "read cin into" or "write to cout from" it), and you never have to think about whether you want atoi() or atof() or whatever.#include <string>#include <sstream>template <typename T>bool parse(T& result, const std::string& source) {  std::stringstream ss(source);  return (ss >> result);  // That version doesn't check for garbage after the number.  // If that's what you meant with this "trimming" business, then you can  // read into a temporary, and assign it back if another read succeeds (i.e.  // there was more garbage at the end):  // T tmp;  // char c;  // bool ok = (ss >> tmp) && (!ss >> c);  // if (ok) { result = tmp; }  // return ok;}int main() {  int x = 42;  float y = 23.0f;  // If I later decide I want x to be a float, or y an int, nothing else changes  // (except the variable initializations of course :) )  // String literals are still char*'s, but they get implicitly converted to  // std::string by the function call. You will find that std::strings are  // much easier to manipulate.  if (!parse(x, "zomg, no int here")) {    // We get here, and x is still 42  }  if (parse(y, "0")) {    // We get here; y is 0.0f, but we know there was a "real" zero  }};  I understand that people generally use strings in c++.  However, I've implemented most of my current project effictively using char*.  By "trim", I mean eliminate whitespace characters from the front and back of the character sequence, so that I can determine if "    0 " is a zero.  I similarly want to figure out how to determine if a string will return 0.0 from atof.   ;Quote:Original post by gamechampionxI understand that people generally use strings in c++.  However, I've implemented most of my current project effictively using char*.Revising an existing codebase to reflect current practice can be a chore, but it's worth it. If your dead set against it though, you should at least do so in your next 'from scratch' project.Quote:By "trim", I mean eliminate whitespace characters from the front and back of the character sequence, so that I can determine if "    0 " is a zero.  I similarly want to figure out how to determine if a string will return 0.0 from atof.Fortunately, trimming will only decrease the size of a string, and so is a less error-prone operation than some others. Trimming the front will involve incrementing the start pointer if it's safe to do so (*shudder*), or shifting the data backward. Trimming from the end will just involve storing a zero in the appropriate location. Determining if the value is a valid real number will involve checking for digits and the characters +, - and . in the appropriate order (and perhaps others if you want to support other notations). I believe there was some code posted for this previously.However, if you do enough of this sort of hacking, eventually you will encounter undefined behavior and you will spend some amount of time tracking down bugs related to string manipulation. Will it be more time than it would take to switch to std::string, the standard library, and possibly boost? Or less? I don't know, but in the end you've got to ask yourself one question: 'Do I feel lucky?' :-) </clint eastwood reference>   ;  The function strtod will return an additional piece of information that allows you to tell if the conversion/parse failed or not. It gives you a pointer that tell where the scan stopped. If that pointer points to the string's NULL terminator, then the parse is valid.No trimming is needed if all the white space is in-front of the number.Trimming from the end is a matter of scanning, starting from the end of the string torward the beginning, and nulling white-space characters until we hit a non-whitespace character.//Removes all ws from right to leftchar* eatwsright(char* w){int v = strlen(w)-1;   while(v >= 0)   {if(isspace(w[v]))   w[v] = '\0';else  return w;v--;   }return w;}//Side-effect - may modify input stringbool is_a_number(char* chxx,double& f_out){char* ch = eatwsright(chxx);//Remove whitespace of string end   char* endp;//Will hold address of where scan ended   f_out = strtod(ch,&endp);//Parse stringint len = strlen(ch);////Check if parsing ended correctlyif(endp == ch || (endp != (ch+len)))  return falsereturn true;}