从C中的getchar()获取一个大整数?
我正在读取一个带有“$”分隔值的文件,比如W$65345$23425,并且一直在使用getchar()获取值(而n=getchar()!=“$”),等等。当我得到第二个值时,我创建一个整数列表,并用getchar()填充该列表,因此我非常确定我有一个 [6,5,3,4,5]. 如何将其转换为值为65345的int? 这是我的密码:从C中的getchar()获取一个大整数?,c,input,integer,text-files,getchar,C,Input,Integer,Text Files,Getchar,我正在读取一个带有“$”分隔值的文件,比如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;
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 ;
}
试试这个
int read_data()
{
int n = getchar();
int ret = 0;
while(n != '$')
{
ret = 10 * ret + n - '0';
n = getchar();
}
return ret;
}
请注意,
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);
getchar()
的返回类型是int
,而不是char
。您应该首先解决这个问题。使用strtol
将字符串转换为数字。pb=&j对不起,这条线让我饿了。不,请在这里RTFM:多余的条件。当n>='0'&&n