歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

將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. { 
  14.     using namespace std; 
  15.  
  16.     char digit_string[MAX]; //保存字符'0'---'9'的數組  
  17.     char next; 
  18.     int index = 0; 
  19.     cout<<"Enter an integer and press return:"; 
  20.     cin.get(next); 
  21.     while (next != '\n') 
  22.     { 
  23.         if( isdigit(next) && (index < MAX-1) ) ///丟棄不屬於'0'--'9'的字符  
  24.         { 
  25.             digit_string[index] = next; 
  26.             index++; 
  27.         } 
  28.         cin.get(next); 
  29.     } 
  30.     cout<<endl<<endl; 
  31.     cout<<"String converts to the integer :"; 
  32.     cout<<atoi(digit_string); ///***********  
  33.     cout<<endl; 
  34.     return 0; 
  35. } 

Copyright © Linux教程網 All Rights Reserved