我需要找到文件中一组数字的反转度数。
我从 .txt
文件中读取输入,格式如下:
SET 1: -3 1 2 0 4
SET 2: 0 1 2 3 4 5
SET 4: 29 39 0 1 3
我不知道如何分离输入(集合及其编号)。我想把它们放在一个结构中,但到目前为止它没有用。 反转度 = 小于其索引值的数字的数量。例如,在 SET 2 中,反转度为 0。
最佳答案
您需要在卡住的地方发布代码;这是获得帮助的最佳方式。 无论如何,这里有一些粗略的代码可以帮助您确定问题出在哪里。我一直保持简单,让您了解 vanilla C 如何执行 I/O。
#include <stdio.h> /* snprinf, fprintf fgets, fopen, sscanf */
int main(void)
{
char line_buffer[64];
FILE* infile = fopen("yourfile.txt", "r"); /* open file for reading */
while(fgets(line_buffer, 64, infile) != NULL)
{
char set_name[8]; /* construct a string w/ the set number */
snprintf(set_name, 8, "SET %c:", *(line_buffer+4)); /* no. is 5th char */
fprintf(stdout, "%s ", set_name); /* fprintf w/ stdout = printf */
int set[8];
int ind = 0;
for(int i=7; line_buffer[i]!='\0';) /* start from first number and end */
{ /* when string ends, denoted by the '\0' sentinel */
int n; /* using pointer arithmetric, read in and store num & consume */
sscanf(line_buffer+i, "%d %n", set+ind, &n); /* adjacent whitespace */
i += n; /* n from sscanf tells how many chars are read in */
fprintf(stdout, "%d ", set[ind]);
ind +=1;
}
fprintf(stdout, "\n");
}
return 0;
}
关于c - 如何在c中将文件中的单词与数字分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839157/