C++ Tutorial/Data Types/convert from string

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Using atof.

<source lang="cpp">#include <iostream> using std::cout; using std::endl;

  1. include <cstdlib>

using std::atof; int main() {

  double d = atof( "99.0" );
  cout << d / 2.0 << endl;
  return 0;

}</source>

49.5

Using atoi

<source lang="cpp">#include <iostream> using std::cout; using std::endl;

  1. include <cstdlib>

using std::atoi; int main() {

  int i = atoi( "2593" );
  cout << i - 593 << endl;
  return 0;

}</source>

2000

Using atol

<source lang="cpp">#include <iostream> using std::cout; using std::endl;

  1. include <cstdlib>

using std::atol; int main() {

  long x = atol( "1000000" );
  cout << x / 2 << endl;
  return 0;

}</source>

500000

Using strtod

<source lang="cpp">#include <iostream> using std::cout; using std::endl;

  1. include <cstdlib>

using std::strtod; int main() {

  double d;
  const char *string1 = "51.2 are admitted";
  char *stringPtr;
  d = strtod( string1, &stringPtr );
  cout << d << endl;
  return 0;

}</source>

51.2

Using strtol

<source lang="cpp">#include <iostream> using std::cout; using std::endl;

  1. include <cstdlib>

using std::strtol; int main() {

  long x;
  const char *string1 = "-1234567abc";
  char *remainderPtr;
  x = strtol( string1, &remainderPtr, 0 );
  cout << x << " " << remainderPtr << " " << x + 567 << endl;
  return 0;

}</source>

-1234567 abc -1234000

Using strtoul

<source lang="cpp">#include <iostream> using std::cout; using std::endl;

  1. include <cstdlib> // strtoul prototype

using std::strtoul; int main() {

  unsigned long x;
  const char *string1 = "1234567abc";
  char *remainderPtr;
   x = strtoul( string1, &remainderPtr, 0 );
  cout << x << "  "<< x - 567 << endl;
  return 0;

}</source>

1234567  1234000