gpt4 book ai didi

c - 从 char 数组中解析 int

转载 作者:行者123 更新时间:2023-11-30 19:12:40 25 4
gpt4 key购买 nike

我正在尝试读取边缘以空格分隔的图表。从 char* 缓冲区解析到整数时出现问题。

示例图:

1   2 
1 3
2 3
3 4
4 5
1 5
5 6
1 6

输出:

first edge: 1
second edge: 2
first edge: 0
second edge: 0
first edge: 1
second edge: 3
first edge: 0
second edge: 0
first edge: 2
second edge: 3
first edge: 0
second edge: 0
first edge: 3
second edge: 4
first edge: 0
second edge: 0
first edge: 4
second edge: 5
first edge: 0
second edge: 0
first edge: 1
second edge: 5
first edge: 0
second edge: 0
first edge: 5
second edge: 6
first edge: 0
second edge: 0
first edge: 0
second edge: 0
first edge: 1
second edge: 6
first edge: 0
second edge: 0
first edge: 0
second edge: 0

显然所有这些零不应该在那里。

代码:

#include <stdio.h>
#include <math.h>
#include <ctype.h>

int main(int argc, char* argv[]){

FILE *fin;
fin = fopen(argv[1], "r");
int n_e = 0;
char* buffer = (char*)malloc(2048);
char* n1 = (char*)malloc(256);
char* n2 = (char*)malloc(256);
int v_1 = 0;
int v_2 = 0;
int flag = 0;

while(!feof(fin)){
int bytes_read = fread(buffer, 1, 2048, fin);
for(int i = 0; i < bytes_read; i++){
if(isdigit(buffer[i])){
if(flag == 0){
n1[v_1++] = buffer[i];
}
else
n2[v_2++] = buffer[i];
}
else if(buffer[i] == ' ')
flag = 1;
else{ //end of the line??
n_e++;
flag = 0;
n1[v_1++] = '\0';
n2[v_2++] = '\0';
int first = atoi(n1);
int second = atoi(n2);
printf("first edge: %d\n", first);
printf("second edge: %d\n", second);
v_1 = 0;
v_2 = 0;
}
}
}

return 0;
}

最佳答案

您可以在一行中实现您想要的核心:fscanf 行。剩下的部分专门用于框架和错误检查——这是任何程序的重要组成部分。将图形边缘作为文本文件给出:

#include <stdio.h>

int main(int argc, char *argv[]) {
FILE *fin;
int first, second;
if(argc < 2) { // check # arguments
return 0; // or other action
}
fin = fopen(argv[1], "rt");
if(fin == NULL) { // check the file opened
return 0; // or other action
}
while(fscanf(fin, "%d%d", &first, &second) == 2) { // check the number of items read
printf("first edge: %d, second edge: %d\n", first, second);
}
fclose(fin);
return 0;
}

程序输出:

first edge: 1, second edge: 2
first edge: 1, second edge: 3
first edge: 2, second edge: 3
first edge: 3, second edge: 4
first edge: 4, second edge: 5
first edge: 1, second edge: 5
first edge: 5, second edge: 6
first edge: 1, second edge: 6

另请注意,feof 的使用方式与您的方式不同,如上面所评论的。

关于c - 从 char 数组中解析 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36701511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com