我正在读取一个'$'分隔值的文件,如W $ 65345 $ 23425,并且一直使用getchar()来获取值(而n = getchar()!='$')等等。当我到达第二个值时,我创建一个整数列表并用getchar()填充该列表,所以我很确定我有一个列表 [6,5,3,4,5]。如何将其转换为值为65345的int? 这是我的代码:
void read_data(char* pa,int* pb,double* pc){
int n;
pa = &n;
n = getchar();
int j[25];
int m = 0;
while ((n=getchar()) != '$'){
j[m] = n;
m++;
}
pb = &j;
n = getchar();
int x[25];
m = 0;
while ((n=getchar()) != '$'){
x[m] = n;
m++;
}
pc = &x;
return ;
}
答案 0 :(得分:2)
试试这个
int read_data()
{
int n = getchar();
int ret = 0;
while(n != '$')
{
ret = 10 * ret + n - '0';
n = getchar();
}
return ret;
}
答案 1 :(得分:0)
请注意,getchar
会将读取的字符作为unsigned char
广告投放回int
。这意味着下面的语句指定由getchar
-
j[m] = n;
您可以使用标准库函数strtol
将字符串转换为long int
。您必须将int
数组更改为char
数组。
char *endptr; // needed by strtol
// note that the size of the array must be large enough
// to prevent buffer overflow. Also, the initializer {0}
// all elements of the array to zero - the null byte.
char j[25] = {0};
int m = 0;
while ((n = getchar()) != '$'){
j[m] = n;
m++;
}
// assuming the array j contains only numeric characters
// and null byte/s.
// 0 means the string will be read in base 10
int long val = strtol(j, &endptr, 0);