[英]Read each line from a file and split the line into a string and an array in C
作業 -我分配了一個程序來讀取文件。 該文件如下所示:
B 34 55 66 456 789 78 59 2 220 366 984 132 2000 65 744 566 377 905 5000
I 9000
I 389
Dm
DM
其中B
是從數字數組構建二進制堆(B后面的數字。我是在數組/堆中插入一個數字Dm是刪除最小值,而DM是刪除最大值。
我已經為堆編寫了代碼,並且可以用random numbers
填充數組。 我的問題是讀取first line
並將其解析為string B
和array
。
我嘗試使用以下代碼,但顯然不起作用。
char line[8];
char com[1];
int array[MAX] //MAX is pre-defined as 100
FILE* fp = fopen( "input_1.txt", "r" );
if( fp )
{
while( fgets ( line, sizeof(line), fp ) != NULL )
{
sscanf(line, "%s" "%d", &com, &array );
... //Following this, I will have a nested if that will take
each string and run the appropriate function.
if ( strcmp( com, "B" ) == 0 )
{
fill_array( array, MAX );
print_array( array, MAX );
}
我已經閱讀了大約6個小時,總共3天,但無法找到解決我問題的方法。 任何幫助都會很棒。
這是一個小程序,它將打開一個文件,讀出1行,並在空格附近分割它找到的內容:
void main()
{
char str[50];
char *ptr;
FILE * fp = fopen("hi.txt", "r");
fgets(str, 49, fp); // read 49 characters
printf("%s", str); // print what we read for fun
ptr = strtok(str, " "); // split our findings around the " "
while(ptr != NULL) // while there's more to the string
{
printf("%s\n", ptr); // print what we got
ptr = strtok(NULL, " "); // and keep splitting
}
fclose(fp);
}
所以我要在包含以下內容的文件上運行此文件:
B 34 55 66 456 789 78 59 2 220
我可以期待看到:
B 34 55 66 456 789 78
B
34
55
66
456
789
78
我認為您可以看到如何修改此設置以幫助自己。
首先, line
數組的大小可能應該大於8,可能類似於char line[256]
。 com
數組也是如此,該數組至少應包含3個字符。
char line[256];
char com[3];
您必須使用fgets(line, sizeof(line), fp)
讀取文件fgets(line, sizeof(line), fp)
並使用strtok()
將命令與命令參數分開。
char separators[] = " ";
fgets(line, sizeof(line), fp);
char * p = strtok(line, separators); // p will be a pointer to the command string
strncpy(&com, p, sizeof(com)); // copy the command string in com
// If the command is B, read an array
if (strcmp(com, "B") == 0) {
p = strtok(NULL, separators);
while (p != NULL) {
int value_to_add_to_your_array = atoi(p);
// ... add code to add the value to your array
p = strtok(NULL, separators);
}
// ... call the function that creates your heap
}
// ... add code to handle the other commands
想法是逐行讀取文件,然后針對每一行首先讀取命令,並根據其值確定應以哪種方式讀取其余部分。
在上面的代碼中,我考慮了B
命令,為此我添加了代碼以讀取數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.