[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppStrIsInt

(C++) Check if a std::string can be converted to an integer

  1. include <iostream>
  2. include <sstream>
  3. include <cassert>
///Checks whether a std::string can be converted to an integer. ///Returns true if possible, also returning this integer by referencing. ///Returns false otherwise, setting the referenced integer to zero. bool isInt(const std::string& s, int& rInt) { std::istringstream i(s); if (!(i >> rInt)) { rInt = 0; return false; } return true; } int main() { int value = 69; assert( isInt("IamNoInt", value) == false ); assert( isInt("69", value) == true ); if (isInt("123",value)==true) { std::cout << "The value is an integer" << std::endl; std::cout << "Its square is: " << value*value << std::endl; } else { std::cout << "The value is not integer" << std::endl; } }


Other code snippets

(C++ Builder) Check if an AnsiString can be converted to an integer

Topic links



last edited (November 4, 2006) by bilderbikkel, Number of views: 5310, Current Rev: 10 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.