Linux下C語言字串操作之字串轉數值型

來源:互聯網
上載者:User

1,字串轉整型(一)
#include <stdlib.h>
int atoi(const char *nptr);
字串轉化為整型
long atol(const char *nptr);
字串轉化為長整型
long long atoll(const char *nptr);
long long atoq(const char *nptr);
字串轉化為long long 類型
英文手冊很簡單,直接上
說明:The atoi() function converts the initial portion of the string pointed to by nptr to int.  The behavior is the same as strtol(nptr, (char **) NULL, 10); except that atoi() does not detect errors. The  atol() and atoll() functions behave the same as atoi(), except that they convert the initial portion of the string to their return type of long or long long.  atoq() is an obsolete name for atoll().

2,字串轉整型(二)
#include <stdlib.h>
long int strtol(const char *nptr, char **endptr, int base);
字串轉長整型,base參數為進位,如轉化為10進位,則base應該為10
long long int strtoll(const char *nptr, char **endptr, int base);
字串轉化為long long int
說明:詳細說明請參考man手冊。

3,字串轉浮點數
#include <stdlib.h>
double strtod(const char *nptr, char **endptr);
字串轉 雙精確度浮點數 double 類型
float strtof(const char *nptr, char **endptr);
字串轉 單精確度浮點數 float 類型
long double strtold(const char *nptr, char **endptr);
字串轉 long double 類型

有了以上庫函數,可以很方便的把字串轉化為數值型,真系灰常的方便啊,有木有?

範例程式碼:

#include <stdio.h>
#include <stdlib.h>
int main()

{

  char *str_int="892";
  int int_val=atoi(str_int);
  printf("字串轉整型:%d\n",int_val);
  long long_val=atol(str_int);
  printf("字串轉長整型:%ld\n",long_val);
  char *str_float="238.23";
  char *endptr;
  float float_val=strtof(str_float,&endptr);
  printf("字串轉單精確度浮點型:%f\n",float_val);
  double double_val=strtod(str_float,&endptr);
  printf("字串轉雙精確度浮點型:%f\n",double_val);
  char *str_long="9839282";
  int base=10;
  long long_v=strtol(str_long,&endptr,base);
  printf("strtol : %ld\n",long_v);
  return 0;
}

代碼輸出:

  1. 字串轉整型:892
  2. 字串轉長整型:892
  3. 字串轉單精確度浮點型:238.229996
  4. 字串轉雙精確度浮點型:238.230000
  5. strtol : 9839282


說明:以上各函數的man手冊都有詳盡的解釋,詳情請查閱man手冊。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.