【发布时间】:2013-03-08 21:31:48
【问题描述】:
我正在尝试从具有如下输入的 c 文件中获取整数:
(0 3 200 3) (0 9 500 3) (98 20 500 3) (100 1 100 3) (100 100 500 3)
atoi 和 s 适用于括号后的第一个数字(我使用 while 循环和大于一位数的 strcat 数字)和任何只有一位数的数字,但它们只返回不是数字的第一个数字就在括号之后。
以下是该方法的代码:
void allProcesses(FILE file, struct process processArray[]) {
char ch;
int number;
int a, b, c, io;
int arrayCount = 0;
int processIndex = 0;
char temp[1];
while ((ch = fgetc(&file)) != EOF) {
if (isdigit(ch)) {
char numberAppended[20] = "";
while (isdigit(ch)) {
temp[0] = ch;
strcat(numberAppended, temp);
ch = fgetc(&file);
}
char* end;
number = (int)strtol(numberAppended, &end, 0);
printf("The number is %d\n",number);
int atoinum = atoi(numberAppended);
switch (processIndex) {
case 0:
a = number;
if (DEBUG == TRUE) {
printf("a = %c\n", a);
printf("NUmber a is %d\n", a);
}
processIndex++;
break;
case 1:
b = number;
if (DEBUG == TRUE) {
printf("b = %c\n", b);
printf("NUmber b is %d\n", b);
}
processIndex++;
break;
case 2:
c = number;
if (DEBUG == TRUE) {
printf("c = %c\n", c);
printf("NUmber c is %d\n", c);
}
processIndex++;
break;
case 3:
io = number;
if (DEBUG == TRUE) {
printf("io = %c\n", io);
printf("NUmber io is %d\n", io);
}
processIndex++;
break;
default:
break;
}
}
if (ch == ')') {
processArray[arrayCount] = makeProcess(a, b, c, io);
arrayCount++;
processIndex = 0;
}
}
}
【问题讨论】:
-
顺便问一下
temp是什么?是否保证temp[1]为0? -
在进入这段代码之前如何设置
ch?问题可能出在您没有发布的周围循环中。 -
@user
processIndex在哪里更新? -
char temp[1];使strcat(numberAppended, temp);在temp[0] = ch;之后出现未定义的行为。 -
@DanielFischer 是的未定义其行为