【问题标题】:How to print a string based on the postion in c?如何根据c中的位置打印字符串?
【发布时间】:2020-01-30 15:39:02
【问题描述】:

我正在处理一个问题,该问题要求我在该位置打印一个给定 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++;
        }
    }
}

我是初学者。这段代码应该很容易理解。

【问题讨论】:

  • 您自己进行标记化,虽然语言已经提供了一个:看看strtok
  • 是的,但我必须在这里从头开始编写自己的逻辑。
  • 因为最后一个 if 语句。否则[i-1] 将是-1,导致错误。不是很好
  • 是的,可以使用sscanf。你能告诉我怎么做吗?
  • sscanf 不知道有多少字,怎么用。

标签: c string file tokenize


【解决方案1】:

这应该适用于所有情况,

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;
}

【讨论】:

  • 为什么使用count == field_number
  • count == field_number 时,你已经打印了这个单词,现在你应该等到下一行。然后你可以开始计算单词并打印出单词field_number告诉你打印。
  • 这不是打印预期的输出。
猜你喜欢
  • 2017-06-11
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多