2010-12-21 67 views
0

我想将字符串转换为整数。但我的字符串是234,23,34,45.如果我使用atoi,它只给我提供了234.我想转换所有整数在我的string.How我可以使用atoi来解决这个问题,或者我可以使用什么来代替atoi?在C中使用atoi()函数

+0

您想每个分隔的数字转换?尝试将它们分成数组数组。 – 2010-12-21 21:21:14

+1

你的意思是你想要234233445还是{234,23,34,45}? – Mikel 2010-12-21 21:28:07

+0

我的意思是{234,23,34,45}每个人 – fasaw 2010-12-21 21:38:38

回答

4

一种选择是使用strtok()将你的字符串分成几部分,然后在每个部分使用atoi()。

编辑:(在评论dmckee推荐)

  • 警告#1:strtok的保持一个指针调用之间的串;它不是线程安全的。
  • 警告#2:strtok损坏传递给它的字符串,将空字符替换为标记末尾的分隔符。
0

您可以解析字符串并将其拆分为“,”,然后将范围传递给atoi()。

1

因为一个字符串只是一个char *提前一个临时的char *每次调用后ATOI到的下一个实例“” + 1

0

你为什么不首先规格化字符串?

这是一个(未经测试)的功能。那么

#include <ctype.h> 
#include <string.h> 

/* 
* remove non-digits from a string 
* 
* caller must free returned string 
*/ 
char *normalize(char *s) 
{ 
    int i, j, l; 
    char *t; 
    l = strlen(s); 
    t = malloc(l+1); 
    for (i = 0, j = 0; i < l; i++) { 
     if (isdigit(s[i])) 
      t[j++] = s[i]; 
    } 
    t[j] = '\0'; 
    return t; 
} 

代替

int intvalue = atoi(numstring); 

做到这一点

char *normalized = normalize(numstring); 
int intvalue = atoi(normalized); 
0
int my_atoi(const char * str) { 

    if (!str) 
    return 0; // or any other value you want 

    int str_len = strlen(str); 
    char *num_str = (char *)malloc(str_len * sizeof(char)); 

    int index = 0; 
    for (int i = 0; i < str_len; ++i) { 
    char ch = str[i]; 

    if (ch == 0) { 
     num_str[index] = 0; 
     break; 
    } 

    if (isdigit(ch)) 
     num_str[index++] = ch; 
    } 
    num_str[index] = 0; 

    int ret = atoi((const char *)num_str); 
    free(num_str); 
    return ret; 
} 

然后调用my_atoi(const char *)功能:

char *str = "234,23"; 
int v = my_atoi(str); 
1

假设你想要{234,23,34,45}。

使用,和strchr

#include <string.h> 

void print_nums(char *s) 
{ 
    char *p; 

    for (p = s; p != NULL; p = strchr(p, ','), p = (p == NULL)? NULL: p+1) { 
     int i = atoi(p); 
     printf("%d\n", i); /* or whatever you want to do with each number */ 
    } 
} 

或许更容易阅读:

void print_nums(char *s) 
{ 
    char *p = s;   /* p always points to the first character of a number */ 

    while (1) { 
     int i = atoi(p); 
     printf("%d\n", i); /* or whatever you want to do with each number */ 

     p = strchr(p, ','); /* find the next comma */ 
     if (p == NULL) 
      break; /* no more commas, end of string */ 
     else 
      p++; /* skip over the comma */ 
    } 
} 

使用的strtok

#include <string.h> 
#include <stdio.h> 
#include <stdlib.h> 

void print_nums(const char *str) 
{ 
    char *tempstr = strdup(str); 
    char *p = NULL; 
    const char *delim = ","; 

    for (p = strtok(tempstr, delim); p != NULL; p = strtok(NULL, delim)) { 
     int i = atoi(p); 
     printf("%d\n", i); /* or whatever you want to do with each number */ 
    } 

    if (tempstr != NULL) { 
     free(tempstr); 
     tempstr = NULL; 
    } 
}