gpt4 book ai didi

c - strtok 和数组存储 : output not as expected

转载 作者:行者123 更新时间:2023-11-30 16:55:06 24 4
gpt4 key购买 nike

在下面的代码中,文件 test.txt 具有以下数据:
192.168.1.1-90
192.168.2.2-80

这个输出不符合预期。我期望输出是
192.168.1.1
90
192.168.2.2
80
任何帮助将不胜感激。

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char *result[10][4];
int i=0;
const char s[2] = "-";
char *value,str[128];
fp = fopen("test.txt", "r");
if (fp == NULL)
printf("File doesn't exist\n");
else{
while(!feof(fp)){

if(fgets(str,sizeof(str),fp)){

/* get the first value */
value = strtok(str, s);
result[i][0]=value;
printf("IP : %s\n",result[i][0]); //to be removed after testing


/* get second value */
value = strtok(NULL, s);
result[i][1]=value;
printf("PORT : %s\n",result[i][1]); //to be removed after testing
i++;
}}
for (int k=0;k<2;k++){
for (int j=0;j<2;j++){
printf("\n%s\n",result[k][j]);
}
}

}
return(0);
}

最佳答案

您可以尝试这个解决方案。它使用动态内存来代替,但会做你想要的事情。

代码:

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

#define BUFFSIZE 128

void exit_if_null(void *ptr, const char *msg);

int
main(int argc, char const *argv[]) {
FILE *filename;
char buffer[BUFFSIZE];
char *sequence;
char **ipinfo;
int str_size = 10, str_count = 0, i;

filename = fopen("ips.txt", "r");

if (filename == NULL) {
fprintf(stderr, "%s\n", "Error Reading File!");
exit(EXIT_FAILURE);
}

ipinfo = malloc(str_size * sizeof(*ipinfo));
exit_if_null(ipinfo, "Initial Allocation");

while (fgets(buffer, BUFFSIZE, filename) != NULL) {
sequence = strtok(buffer, "-\n");

while (sequence != NULL) {
if (str_size == str_count) {
str_size *= 2;
ipinfo = realloc(ipinfo, str_size * sizeof(*ipinfo));
exit_if_null(ipinfo, "Reallocation");
}

ipinfo[str_count] = malloc(strlen(sequence)+1);
exit_if_null(ipinfo[str_count], "Initial Allocation");

strcpy(ipinfo[str_count], sequence);

str_count++;

sequence = strtok(NULL, "-\n");
}
}

for (i = 0; i < str_count; i++) {
printf("%s\n", ipinfo[i]);
free(ipinfo[i]);
ipinfo[i] = NULL;
}

free(ipinfo);
ipinfo = NULL;

fclose(filename);

return 0;
}

void
exit_if_null(void *ptr, const char *msg) {
if (!ptr) {
printf("Unexpected null pointer: %s\n", msg);
exit(EXIT_FAILURE);
}
}

关于c - strtok 和数组存储 : output not as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40394719/

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