【问题标题】:Read only certain strings from file仅从文件中读取某些字符串
【发布时间】:2015-01-24 13:29:19
【问题描述】:

我想使用rand() 生成随机名称,并将每个名称链接到一个整数(例如,1 代表丹尼尔,2 代表莎拉,依此类推)。我写了函数void random_name () 并使用switch 链接每个数字rand() 返回一个名称,但现在我想使用文件来执行此操作。例如,如何仅从文件中读取以 1 开头的行?谢谢:)

【问题讨论】:

  • 你试过什么?可以发帖吗?
  • 获取一个随机数然后从文件中读取那么多行,将最后读取的行的内容作为实际名称不是更容易吗?在这种情况下,每一行将只包含一个名称。 int rand = rand(); while ( fgets ( line, sizeof line, file ) != NULL && r) { r--; } // here line would contain the contents of the line at the random position 类似的东西。
  • 要了解行首的内容,您需要阅读该行。
  • @Cyclone 我没想到!这可能是最简单的解决方案。
  • 这会如何工作?要了解书页上写的内容,您需要阅读该页,不是吗?

标签: c file random


【解决方案1】:

如果您想在每一行上都有一个数字和一个名称,您必须阅读每一行以查找随机生成的数字。实现这一目标的一种方法是这样的:

srand(time(0));
// random number between 1 and 10
int r = rand() % 10 + 1;
char line[128];
char name[64];
int number;
FILE* file = fopen("names.txt", "r");
if(file) {
    // loop while not EOF 
    while(fgets(line, sizeof line, file) != NULL) {
        // scan the line for a number and a name
        sscanf(line, "%d %s", &number, name);
        // if the number is equal to the random one break the loop
        if(number == r) {
            printf("random name is %s\n", name);
            break;
        }
    }
    fclose(file);
}

如果你在每一行只有一个名字并且至少有 10 个不同的名字,这会起作用:

srand(time(0));
int r = rand() % 10 + 1;
char line[128];
FILE* file = fopen("names.txt", "r");
if(file) {
    // loop while not EOF and r > 0, when r is 0 then we have
    // read r amount of lines from the file
    while(fgets(line, sizeof line, file) != NULL && --r);
    printf("random name is %s\n", line);
    fclose(file);
}

【讨论】:

  • 为什么是“--r”?很抱歉打扰你,但我真的是编程新手..
  • @SCoder: rn 编号行的倒计时。因此,当r==0fgets 失败时循环将停止,并且在这两种情况下都会显示最后一行读取。
猜你喜欢
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多