如何只读取每行的第一个单词? [英] How to read only the first word from each line?
问题描述
我做了很多简单的程序,但是我只是试图从文本文件的每一行读取第一个字到 char字符[30]
。
我试过了,但是没有成功。哦,我每次读它都必须重用这个字符。 (每次阅读时都要输入一个有序的列表)。
任何人都可以给我一种从文件中读取这种方式的方法,用简单的cleany
FILE * fp;
char char [30];
fp = fopen(/ myhome / Desktop / tp0_test.txt,r);
if(fp == NULL){
printf(Erro ao abrir ficheiro!\\\
);
} else {
while(!feof(fp)){
fscanf(fp,%* [^ \\\
]%s,word); //不能很好地工作...
printf(word read is:%s\\\
,word);
strcpy(word,); //它是否正确?
}
}
fclose(fp);
例如,对于包含以下内容的文件:
word1 word5
word2 kkk
word3 1322
word4 synsfsdfs
只打印这个:
读取的单词是:word2
单词读取是:word3
单词是:word4
单词是:
* [^ \\\
]%s,word); //不能很好地工作...
fscanf(fp,%s%* [^ \\\
],word);
读取第一个单词并忽略其余部分,而不是忽略该行并读取第一个单词。 / p>
编辑一些解释
%s忽略空格,所以如果输入缓冲区有42,scanf会忽略第一个空格,将forty复制到目的地,并把缓冲区放在two之前的空格处。
%* [^ \\\
]会忽略换行符之前的所有内容,不包括换行符。因此,一个包含one \\\
two的缓冲区在scanf之后的换行符处被定位(就好像它是\\\
two)
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.
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:
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.
Edit some 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"
%*[^\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")
这篇关于如何只读取每行的第一个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!