0

我想更新和比较文件。如何编写代码以获得以下结果?

第一次运行程序,获取数据akon : 5,我需要保存到 txt 文件中:

akon : 5

第二次运行,获取数据john : 10

akon : 5
john : 10

第三次运行,获取数据akon : 2

akon : 2
john :10

第四次运行,获取数据akon : 3

akon : 3
john : 10

下面是我输入的代码,但我被困在这里。

FILE *out_file; 
char name[100];
int score;

printf("please enter name:");
gets(name);

printf("please enter the score:");
scanf("%d",&score);
out_file= fopen("C:\\Users/leon/Desktop/New Text Document.txt", "w"); // write only 

      // test for files not existing. 
      if (out_file == NULL) 
        {   
          printf("Error! Could not open file\n"); 
          exit(-1); // must include stdlib.h 
        } 

      // write to file 
      fprintf(out_file, "%s : %d",name,score); // write to file 
4

1 回答 1

0

我建议先尝试用 Python 等高级语言对你想要的东西进行原型设计。以下 python 代码可以满足您的需求。

您应该能够跟随此代码并找到等效的 C 方法来完成相同的任务。最复杂的部分可能是决定如何存储球员/分数对(在 Python 中是微不足道的,但不幸的是 C 没有字典)。

# Equivalent to C/C++ include
import sys

# Create dictionary to store scores
data = {}

# Check for existence of scores files
try:
    with open("data.txt", 'r'): pass
except IOError: pass

with open("data.txt", 'r') as fp:
    for line in fp:
        # Split line by ':'
        parts = line.split(':')

        # Check that there are two values (name, score)
        if len(parts) != 2: continue

        # Remove white-space (and store in temporary variables)
        name = parts[0].strip()
        score = parts[1].strip()

        # Store the name and score in dictionary
        data[name] = score

# Get input from user
update_name = raw_input('Enter player name: ')
update_score = raw_input('Enter player score: ')

# Update score of individual
data[update_name] = update_score

# Write data to file (and to screen)
with open("data.txt", 'w') as fp:
    for name,score in data.items():
        output = "{0} : {1}".format(name,score)

        print output
        fp.write(output + '\n')

一些提示:

于 2013-08-17T14:17:53.440 回答