我有一个.txt文件,其中包含以下内容:
1 - Ground 2
2 - Ground 7
3 - City 1
4 - Hill x
5 - City 3
6 - City 4
7 - Hill 6
任务是按特定顺序对这些游戏插槽进行排序:文件的第一个列是插槽编号,第二个文件的列是插槽类型,文件的第三个列是插槽右侧插槽的编号< / em>的
x
表示该插槽右侧没有插槽,这意味着插槽4(Hill)是有序插槽中的最后一个插槽。因此,程序必须搜索文本文件以找到x
,然后查看该行上的插槽号是什么,以查看左侧的插槽。完成后,它应输出以下内容:
(5,City)->(3, City)->(1, Ground)->(2,Ground)->(7,Hill)->(6,City)->(4,Hill)
此代码读入文本文件并打印初始插槽列表。任何帮助将不胜感激。感谢。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *SLOTS_FILE_PATH = "slots.txt";
char slotsArr[7][100];
char newSlots[7][100];
int main()
{
int i = 0;
int j;
char search;
FILE *fx = fopen(SLOTS_FILE_PATH, "r+");
if (fx == NULL)
{
perror("Error opening slots file");
i = -1;
}
else
{
while(fgets(slotsArr[i],
sizeof(slotsArr[i]), fx) != NULL)
{
i++;
}
fclose (fx);
}
printf("\n-------Initial List of Slots-------\n");
for (j = 0; j < i; j++)
{
printf("%s", slotsArr[j]);
}
printf("\n-------Sorted List of Slots-------\n");
}
*********************这就是输出的内容******************** *****
-------Initial List of Slots-------
1 - Ground 2
2 - Ground 7
3 - City 1
4 - Hill x
5 - City 3
6 - City 4
7 - Hill 6
-------Sorted List of Slots-------
答案 0 :(得分:0)
在我的浏览器中输入,所以会有拼写错误。 (我一方面有绷带......)但是,一个指针:
char slotsArr[7][100];
char newSlots[7][100];
…
// It starts with x
char charToSearch = 'x'; // It doesn't matter, whether it is a digit or char.
int sortedIndex = 7; // Start at the right side.
while( sortedIndex>0 )
{
// search for the row by iterating over the array and comparing the last letter.
for( int unsortedIndex=6; unsortedIndex>=0; unsortedIndex-- )
{
if( charToSearch == slotsArr[unsortedIndex][16] )
{
charToSearch = slotsArr[unsortedIndex][0]; // The next item's index
sortedIndex--;
// The format of the result array is not clear in your Q.
// However, this is not the problem. I put a number and the trimmed
// string into it. You can add the parenthesis and the - at output,
// if you want to.
newSlots[sortedIndex][0]=charToSearch;
newSlots[sortedIndex][1]=',';
// Copy the string up to a space
char src = slotsArray[unsortedIndex]+7;
char *dest = newSlots[sortedIndex]+2;
while( !isspace(src) )
{
*dst++ = *src++;
}
*dst='\0';
break;
}
}
}