【问题标题】:How can I locate middle character of a word in a text file?如何在文本文件中找到单词的中间字符?
【发布时间】:2012-12-15 11:55:33
【问题描述】:

如何在文本文件中找到第一个单词的中间字符,然后用它来计算该字符的其他出现次数?我有计算文本文件中单词的函数和计算第一个单词长度的函数。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <conio.h>
#define maxBuf 128

void howMany(FILE * file);
void words(FILE * file);

int main() {
FILE *temp, *file;
file = fopen("test.txt", "r");
temp = fopen("temp.txt","w");
char sd1[maxBuf];

howMany(file);
words(file);

fclose(file);
fclose(temp);

unlink("test.txt");
rename("temp.txt","test.txt");

return 0;  
}
void howMany(FILE * file){
char sd1[maxBuf];
file = fopen("test.txt", "r");
int i, z, c;
char word[1000];

while (!feof(file)) {
        if(fscanf(file,"%s",word)==1);
        printf("word read is: %s\n", word);
        printf("word read is: %i\n", strlen(word));                  
        break;
}
}
void words(FILE * file){
file = fopen("test.txt", "r");
char sd1[maxBuf];
int iwant; 
int nwords = 0; 

char word[1000];
int i, z;

while (fscanf(file, "%s", sd1) == 1) {

++nwords;
}
printf("There are %i words. \n", nwords);
}

【问题讨论】:

  • 你坚持哪一部分?随机访问文件?获取文件大小?这个问题很模糊。
  • @JanDvorak 在寻找单词的中间字符。
  • 单词的中间字符 != 文本文件的中间字符
  • 向我们展示您尝试过或考虑过的内容
  • 前者很简单:只需读入字符串,计算其长度,除以二,索引到字符串中。你应该定义如果字符串长度是偶数会发生什么。

标签: c file


【解决方案1】:

缩进你的代码。

检查fopen, fgets等函数的结果...

MAX_BUFmaxBuf 的更好名称

size_t middle, n = strlen(sd1);
middle = (n / 2) + (n % 2 != 0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 2019-12-27
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多