【问题标题】:C: Read words and include \n on them, but not spacesC:阅读单词并在其上包含 \n,但不包含空格
【发布时间】:2013-07-08 12:00:11
【问题描述】:

我需要从 C 中的文件中读取并将每个单词放在一个数组中, 单词中不应包含空格(当它到达空格时,应结束复制该单词),但 \n 必须在找到时包含。

fscanf(arquivo,"%s",palavras[i].string);

几乎可以工作,但是在文件中找到它时不包括 \n..

fgets (temp , 100 , arquivo);

不起作用,因为它在找到空格时不会停止。

你们觉得呢?

【问题讨论】:

  • 最简单的方法是使用 getc() 和一个小型有限状态机逐个字符读取。

标签: c string file fgets scanf


【解决方案1】:

您可以使用fgetssscanf 之类的组合,

ptr = NULL;
ptr = fgets (temp , 100 , arquivo); 
 // Check 1) return value for NULL 2) whether temp has `\n`
 // or read till `\n`

while( ( found = sscanf( ptr, "%s", palavras[i].string ) ) == 1 )
{
    // palavras[i].string has valid string

    ptr += strlen( palavras[i].string ); // next string in
    i++; // next element in array. Overflowing ?
}

strcat( palavras[i].string, "\n" );

提供足够大小的fgets 以保持排队。当然,需要更多的错误检查才能使其稳定。

【讨论】:

  • 不应该是等于1的时候吗?由于sscanf 返回成功读取的项目数?另外,sscanf 不会只是跳过换行符吗?
  • @DrewMcGowen 谢谢,修复了while 循环。接得好。需要一些时间来解决其他问题。
  • @DrewMcGowen 代码已修复。当然,需要更多的错误检查。
【解决方案2】:

我会采取不同的方法来解决这个问题。

int fd,i,j=0;;
fd = open("nameoffile",O_RDONLY);
char buf[128], word[64];
char *words[128];

while (n=read(fd,buf,sizeof(buf))){
     memset(word,0,sizeof(word));
     for (i=0;i<n;i++){
         if (buf[i] != ' ') word[i] = buf[i];
         else {
              words[j] = malloc(sizeof(word));
              words[j] = word;
              j++;
         }
     }
}

这将创建一个字符数组(或字符串)数组,并向每个数组添加字符,直到找到一个空格,在这种情况下,它将跳过它并移动到下一个字符并开始一个新字符串。

【讨论】:

    【解决方案3】:

    如果您想使用 fscanf,您可以使用以下内容:

    fscanf(fp, "%[^ ]", str);
    

    【讨论】:

    • 只是为了解释:这个格式字符串告诉 scanf 读取直到找到一个空格。
    • 但是如果我有一个这样的文件:一二三\n三二一在前三个之后有一个\n,但它不会一直读取直到找到另一个空间吗?所以我的第三个字符串将是“three\nthree”。还是我错了?
    • 是的,没错,所以我猜你想要第二个“三”作为一个新词?
    【解决方案4】:

    fscanf 在这种情况下会在遇到任何类型的空格(包括换行符)时停止。您可以尝试使用fgets 读取整行(包括换行符),然后反复使用strtok 将其拆分。

    例如:

    char temp[100];
    char *tok;
    
    fgets (temp , 100 , arquivo);
    while ((tok = strtok(temp, " ")) != NULL) {
        // 'tok' points to a null-terminated word with no spaces
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-01
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多