过去两天我一直在研究这个问题,但似乎无法找出问题所在。
我正在从文件中读取并将其作为字符串保存到 char 数组中,但是当我尝试strlen()
在字符串上使用时,它会因分段错误而崩溃。
这就是我正在做的事情。
char read_string[25];
fscanf(file, "%s", &read_string);
int length = strlen(read_string);
另一个问题是,当我将 的内容复制read_string
到另一个 char 数组中时,它会在末尾添加随机字符。
这是我正在做的
char input[25];
for(i=0; i<25; i++)
{
if (read_string[i] == '.')
break;
else
input[i] = read_string[i];
}
我需要在句点将字符串读入输入数组之前复制所有内容。
PS我正在使用fscanf()
,因为该文件结构良好。
如果需要,这是我的代码。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main()
{
//variables
FILE *rFile;
int num_states; //number of states
int num_alphabet; //number of alphabets
int num_acstates; //number of accepting states
int ac_state; //the accepting state
char alphabet[num_alphabet]; //alphabet
char read_string[25]; //assuming the input will be maximum of 25 character
char input[25];
int i,j,x; //indexes for the loop
//open the file to read
rFile = fopen("dfa11", "r");
if (rFile != NULL)
{
//do the program here
//read number of states and number of alphabets
fscanf(rFile, "%d %d", &num_states, &num_alphabet);
//read the alphabet
fscanf(rFile, "%s", &alphabet);
//read the state transition table (matrix)
int value = num_states*num_alphabet;
char table[num_states][num_alphabet];
for(i=0; i<num_states; i++)
{
for(j=0; j<num_alphabet; j++)
{
fscanf(rFile, "%d", &table[i][j]);
}
}
//read number of accepting states and accepting state
fscanf(rFile, "%d", &num_acstates);
fscanf(rFile, "%d", &ac_state);
//read the input string from the file
fscanf(rFile, "%s", &read_string);
for(i=0; i<25; i++)
{
if (read_string[i] == '.')
break;
else
input[i] = read_string[i];
}
//strncpy(input, read_string, j);
printf("%d\n", strlen(read_string));
printf("%d\n", strlen(input));
printf("%s\n", read_string);
printf("%s\n", input);
//close the file
fclose(rFile);
}
else
{
printf("File could not be found");
}
}