我有一个 .txt 文件,其中包含以下内容:
1 - Ground 2
2 - Ground 7
3 - City 1
4 - Hill x
5 - City 3
6 - City 4
7 - Hill 6
任务是以特定顺序对这些游戏槽位进行排序:文件的第一列是槽位编号,第二列是槽位编号文件的列是插槽类型,文件的第三列是相关插槽右侧的插槽编号.
x
意味着该槽位的右侧没有槽位,因此这意味着槽位 4(山)是有序槽位中的最后一个槽位。因此程序必须搜索文本文件以找到 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-------
最佳答案
在我的浏览器中输入的,所以会有拼写错误。 (我一只手上有绷带……)但是,一个指针:
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;
}
}
}
关于c - 对 C 中字符串数组的最后一列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42316759/