歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 將C字符串轉換為整數

將C字符串轉換為整數

日期:2017/3/1 10:08:11   编辑:Linux編程
  1. // c string to int.cpp : Defines the entry point for the console application.
  2. //
  3. ///功能::將C字符串轉換為整數
  4. #include "stdafx.h"
  5. #include<iostream>
  6. #include<cstdlib> ////atoi()
  7. #define MAX 65535
  8. int main(int argc, char* argv[])
  9. {
  10. using namespace std;
  11. char digit_string[MAX]; //保存字符'0'---'9'的數組
  12. char next;
  13. int index = 0;
  14. cout<<"Enter an integer and press return:";
  15. cin.get(next);
  16. while (next != '\n')
  17. {
  18. if( isdigit(next) && (index < MAX-1) ) ///丟棄不屬於'0'--'9'的字符
  19. {
  20. digit_string[index] = next;
  21. index++;
  22. }
  23. cin.get(next);
  24. }
  25. cout<<endl<<endl;
  26. cout<<"String converts to the integer :";
  27. cout<<atoi(digit_string); ///***********
  28. cout<<endl;
  29. return 0;
  30. }

Copyright © Linux教程網 All Rights Reserved