gpt4 book ai didi

c - 如何根据c中的位置打印字符串?

转载 作者:行者123 更新时间:2023-11-30 16:06:21 25 4
gpt4 key购买 nike

我正在解决一个问题,需要我在该位置打印给定字段编号的字符串。应从文件中读取字符串。

文件.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;
}

关于c - 如何根据c中的位置打印字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59989519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com