我正在研究一个问题,要求我在该位置给出给定为field-number
的字符串。字符串应从文件中读取。
file.txt
C is a language.
lex lexical analyser
(blank line)
gcc is good
如果field-number
为2(即句子中的第二个单词)。该程序应输出
is
lexical
(NULL)
is
我编写了一个函数,但是认为它不是正确的方法,并且该函数在所有情况下都适用。它应该处理多余的空格或换行符。
while (fgets(buffer, MAX, file) != NULL) {
for (int i = 1; i < strlen(buffer); i++) {
if (count == field_number - 1) {
int j = i;
while (j < strlen(buffer) && buffer[j] != ' ') {
printf("%c", buffer[j++]);
}
printf("\n");
count = 0;
break;
}
if (buffer[i] == ' ' && buffer[i - 1] != ' ') {
count++;
}
}
}
我是初学者。该代码应易于理解。
这适用于所有情况,
int main() {
//FILE* file = fopen(__FILE__, "r");
//int field_number = 2;
int new_line = 0; // var to keep track of new line came or not
int word = 0;
int count = 0;
char c, prev_c;
while ((c = fgetc(file)) != EOF) {
// printf("[%c]", c);
// if a new line char comes it means you entered a new line
if(c == '\n') {
// you have to print the new line here on the output to handle
// empty line cases
printf("\n");
new_line = 1; // when line changes
word = 0; // no word has come in this new line so far
count = 0; // count becomes 0
} else if( c == ' ' && prev_c != ' ') {
if(word)
count++;
if(count == field_number) // if count exceeds field_number
new_line = 0; // wait till next line comes
} else if (new_line && count == field_number - 1) {
printf("%c", c);
} else {
word = 1; // fi a not new line or non space char comes, a word has come
}
prev_c = c;
}
return 0;
}
可以通过使用sscanf
和%n
和一个循环来迭代缓冲区。%n
将捕获扫描处理的字符数。将所需迭代次数的每个scanned
值添加到total
中。
#include <stdio.h>
int main ( void) {
char buffer[] = "C is a language.";
char item[sizeof buffer] = "";
int total = 0;
int scanned = 0;
int iterate = 2;
for ( int each = 1; each < iterate; ++each) {
scanned = 0;
sscanf ( buffer + total, "%*s%n", &scanned);
if ( ! scanned) {
return 0;
}
total += scanned;
}
if ( buffer[total]) {
sscanf ( buffer + total, "%s", item);
printf ( "%s\n", item);
}
return 0;
}