C语言 如何只读取每行的第一个单词?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3756308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:28:38  来源:igfitidea点击:

How to read only the first word from each line?

cfilescanf

提问by neverMind

I've done many simple procedures, but I'm only trying to read the first word into a char word[30], from each line of a text file.

我已经完成了许多简单的过程,但我只是试图将char word[30]文本文件的每一行中的第一个单词读入 a 。

I've tried, but without success. Oh, I have to reuse that char each time I read it. (To put in an ordered list each time I read it).

我试过了,但没有成功。哦,我每次阅读时都必须重复使用该字符。(每次阅读时放入有序列表)。

Can anyone show me a way to read this way from a file, in a simple and "cleany" way?

谁能告诉我一种以简单和“干净”的方式从文件中读取这种方式的方法吗?

FILE *fp;
char word[30];
fp = fopen("/myhome/Desktop/tp0_test.txt", "r");
if (fp == NULL) {
    printf("Erro ao abrir ficheiro!\n");
} else {
    while (!feof(fp)) {
        fscanf(fp,"%*[^\n]%s",word);//not working very well...
        printf("word read is: %s\n", word);
        strcpy(word,""); //is this correct?
    }
}
fclose(fp);

For example for a file that contains:

例如对于包含以下内容的文件:

word1 word5
word2 kkk
word3 1322
word4 synsfsdfs

it prints only this:

它只打印这个:

word read is: word2
word read is: word3
word read is: word4
word read is: 

回答by pmg

Just swap the conversion specifications in your format string

只需交换格式字符串中的转换规范

        // fscanf(fp,"%*[^\n]%s",word);//not working very well...
           fscanf(fp,"%s%*[^\n]",word);

Read the first word and ignore the rest, rather than ignore the line and read the first word.

阅读第一个单词并忽略其余部分,而不是忽略该行并阅读第一个单词。



Editsome explanation

编辑一些解释

%s ignores whitespace, so if the input buffer has " forty two", scanf ignores the first space, copies "forty" to the destination and leaves the buffer positioned at the space before "two"

%s 忽略空格,因此如果输入缓冲区有“四十二”,则 scanf 忽略第一个空格,将“四十”复制到目的地,并将缓冲区保留在“二”之前的空格处

%*[^\n] ignores everything up to a newline, excluding the newline. So a buffer containing "one \n two" gets positioned at the newline after the scanf (as if it was "\n two")

%*[^\n] 忽略换行前的所有内容,不包括换行符。因此,包含“one \n two”的缓冲区被定位在 scanf 之后的换行符处(就好像它是“\n two”一样)

回答by DigitalRoss

so ross$ expand < first.c
#include <stdio.h>

int main(void) {
  char line[1000], word[1000];

  while(fgets(line, sizeof line, stdin) != NULL) {
    word[0] = '
so ross$ expand < first2.c
#include <stdio.h>

int main(void) {
  char word[1000];

  for(;;) {
    if(feof(stdin) || scanf(" %s%*[^\n]", word) == EOF)
      break;
    printf("%s\n", word);
  }
  return 0;
}

so ross$ ./a.out < first2.c
#include
int
char
for(;;)
if(feof(stdin)
break;
printf("%s\n",
}
return
}
'; sscanf(line, " %s", word); printf("%s\n", word); } return 0; } so ross$ ./a.out < first.c #include int char while(fgets(line, word[0] sscanf(line, printf("%s\n", } return }


Update:Ok, here is one that just uses scanf(). Really, scanf doesn't deal well with discrete lines and you lose the option of avoiding word buffer overflow by setting the word buffer to be the same size as the line buffer, but, for what it's worth...

更新:好的,这是一个只使用 scanf() 的方法。实际上, scanf 不能很好地处理离散行,并且您无法通过将字缓冲区设置为与行缓冲区相同的大小来避免字缓冲区溢出,但是,对于它的价值...



 FILE *fPointer,*fWords,*fWordCopy;
char singleLine[150];

fPointer= fopen("words.txt","r");
fWordCopy= fopen("wordscopy.txt","a");

char * pch;
while(!feof(fPointer))
{
    fgets(singleLine,100,fPointer); 
    pch = strtok (singleLine," ,'(");
    fprintf(fWordCopy,pch);
    fprintf(fWordCopy, "\n"); 
}

fclose(fPointer);

回答by Sam

Have a look at this, strtokfunction is what we needed. You may tell to function where to split the string with parameters, like strtok (singleLine," ,'(");. Here it will cut every time it see white space "," " '" and (. strtok (singleLine," ");or just in white spaces.

看看这个,strtok函数就是我们需要的。你可以告诉函数在哪里用参数分割字符串,比如strtok (singleLine," ,'(");. 在这里,每次看到空格“ ”“ '”和 (. strtok (singleLine," ");或仅在空格中。

##代码##

Results

结果