Tej*_*eja 0 c segmentation-fault
我没有明显的理由得到分段错误.我正在使用该strtok函数并将每一行拆分为多个标记并将它们存储在char指针中.我的数据如下:
输入:
200 -> 103 [weight=7];
200 -> 153 [weight=27];
200 -> 53 [weight=9];
200 -> 178 [weight=43];
55 -> 2 [weight=23];
55 -> 14 [weight=50];
55 -> 20 [weight=17];
55 -> 22 [weight=1];
55 -> 74 [weight=7];
55 -> 93 [weight=9];
55 -> 122 [weight=27];
65 -> 8 [weight=27];
65 -> 9 [weight=9];
Run Code Online (Sandbox Code Playgroud)
码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv)
{
char *ipfile,line[80];
FILE *fp;
char *field1,*field2,*field3,*field4,*field5,*field6,mystr[10];
int row,column,weight;
ipfile = (char *)argv[1];
printf("The input file name is %s\n",ipfile);
fp = fopen(ipfile,"r");
if(fp ==NULL) //Checking whether the command line argument was correctly or not.
printf("There is no such file in the directory.\n");
while(fgets(line,80,fp) != NULL)
{
field1 = strtok(line," ");
//row = atoi(field1);
field2 = strtok(NULL," ");
field3 = strtok(NULL," ");
//column = atoi(field3);
field4 = strtok(NULL," ");
field5 = strtok(NULL," ");
//field6 = strtok(NULL," ");
printf("%s\n",field5);
//printf("Row-%d Column - %d Weight - %d\n",row,column,weight);
}
fclose(fp);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
来自评论:
当我尝试打印
field1,field2,field3,field4之后就被打印出来.但是,当我尝试field5和field6我的节目是给分段错误.
在SO用户的建议之后添加代码.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv)
{
char *ipfile,line[80];
FILE *fp;
char *field1,*field2,*field3,*field4,*field5,*field6,mystr[10];
int row,column,weight;
ipfile = (char *)argv[1];
printf("The input file name is %s\n",ipfile);
fp = fopen(ipfile,"r");
if(fp == NULL) //Checking whether the command line argument was correctly or not.
printf("There is no such file in the directory.\n");
while(fgets(line,80,fp) != NULL)
{
field1 = strtok(line," ");
//row = atoi(field1);
field2 = strtok(NULL," ");
field3 = strtok(NULL," ");
//column = atoi(field3);
field4 = strtok(NULL," ");
field5 = strtok(NULL," []=;");
//field6 = strtok(NULL," ");
printf("%s\n",field5);
//printf("Row-%d Column - %d Weight - %d\n",row,column,weight);
}
fclose(fp);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你在空格上拆分字符串,所以这只有4个令牌,而你的代码需要6个:
200 -> 103 [weight=7];
Run Code Online (Sandbox Code Playgroud)
指定" []=;"为分隔符以解决此问题.(或者->当你在它时也包括在内.)
| 归档时间: |
|
| 查看次数: |
548 次 |
| 最近记录: |