将C字符串转换为整数


  1. // c string to int.cpp : Defines the entry point for the console application.  
  2. //  
  3.  
  4. ///功能::将C字符串转换为整数  
  5.  
  6. #include "stdafx.h"  
  7. #include<iostream>  
  8. #include<cstdlib> ////atoi()  
  9.  
  10. #define MAX  65535  
  11.  
  12. int main(int argc, char* argv[]) 
  13.     using namespace std; 
  14.  
  15.     char digit_string[MAX]; //保存字符'0'---'9'的数组  
  16.     char next; 
  17.     int index = 0; 
  18.     cout<<"Enter an integer and press return:"
  19.     cin.get(next); 
  20.     while (next != '\n'
  21.     { 
  22.         if( isdigit(next) && (index < MAX-1) ) ///丢弃不属于'0'--'9'的字符  
  23.         { 
  24.             digit_string[index] = next; 
  25.             index++; 
  26.         } 
  27.         cin.get(next); 
  28.     } 
  29.     cout<<endl<<endl; 
  30.     cout<<"String converts to the integer :"
  31.     cout<<atoi(digit_string); ///***********  
  32.     cout<<endl; 
  33.     return 0; 

相关内容