简体   繁体   English

我如何专门为 C 中的换行符 strcmp?

[英]How do I strcmp specifically for newline in C?

#include <stdio.h>
#include <string.h>

int main() {
    int counter1, counter2;
    char line[200] = ""; //store all words that don't need to be deleted
    char deleteWord[100]; //word that needs to be deleted
    char space;
    char word[100];
    scanf("%s", deleteWord);

    while (1) {
        scanf("%s", word);

        if (feof(stdin))
            break;
        // increment counter of total words
        ++counter1;
        if (strcmp(word, deleteWord) == 0) {
            // see if the word read in == delete word
            // increment counter of deleted words
            ++counter2;
        } else
        if (strcmp(word, " ") == 0) { // space is an actual space
            strcat(line, word);
            strcat(line, " ");
        } else
        if (strcmp(word, "\n")) { // space a new line \n
            strcat(line, word);
            strcat(line, "\n");
        }
    }

    printf("--NEW TEXT--\n%s", line);

    return 0;
}

In summary, my code is supposed to remove a user input string (one or more words) from another user input string (containing or not containing the word(s)) and produce the output.总之,我的代码应该从另一个用户输入字符串(包含或不包含单词)中删除用户输入字符串(一个或多个单词)并生成 output。 The code removes the word but it adds a newline per word for each iteration.该代码删除了单词,但它为每次迭代为每个单词添加了一个换行符。 I believe it is doing this because the expression for the second else if is always true.我相信它这样做是因为第二个else if的表达式总是正确的。 However, when I properly add the strcmp function for the second else if statement, the code does not produce an output at all (no compiler errors - just missing input).但是,当我为第二个else if语句正确添加strcmp function 时,代码根本不会产生 output (没有编译器错误 - 只是缺少输入)。 Why is this happening and how do I do a strcmp function for a newline?为什么会发生这种情况,我该如何做一个strcmp function 换行?

Your read the words with scanf("%s", word) , which poses these problems:您使用scanf("%s", word)阅读了这些单词,这会带来以下问题:

  • all white space is ignored, so you cannot test for spaces nor newlines as you try to do in the loop, and you cannot keep track of line breaks.所有空白都被忽略,因此您无法在循环中尝试测试空格或换行符,并且您无法跟踪换行符。

  • you should tell scanf() the maximum number of bytes to store into the destination array word , otherwise any word longer than 99 characters will cause a buffer overflow and invoke undefined behavior.您应该告诉scanf()存储到目标数组word中的最大字节数,否则任何超过 99 个字符的单词都会导致缓冲区溢出并调用未定义的行为。

  • you should test the return value of scanf() instead of callin feof() which might be true after the last word has been successfully read.您应该测试scanf()的返回值,而不是调用feof() ,这在成功读取最后一个单词后可能为真。 You should simply write the loop as您应该简单地将循环编写为

     while (scanf("%99s", word) == 1) { // increment counter of total words ++counter1;...
  • you do not test if the words fit in the line array either, causing a buffer overflow if the words kept amount to more than 199 characters including separators.您也不测试单词是否适合line阵,如果单词保留的字符数超过 199 个(包括分隔符),则会导致缓冲区溢出。

To delete a specific word from a stream, you could read one line at a time and delete the matching words from the line:要从 stream 中删除特定单词,您可以一次读取一行并从该行中删除匹配的单词:

#include <ctype.h>
#include <stdio.h>
#include <string.h>

int main() {
    char deleteWord[100]; //word that needs to be deleted
    char line[1000]; //store all words that don't need to be deleted

    printf("Enter the word to remove: ");
    if (scanf("%99s", deleteWord) != 1)
        return 1;

    // read and discard the rest of the input line
    int c;
    while ((c = getchar()) != EOF && c != '\n')
        continue;

    size_t len = strlen(deleteWord);
    printf("Enter the text: ");
    while (fgets(line, sizeof line, stdin)) {
        char *p = line;
        char *q;
        while ((p = strstr(p, deleteWord)) != NULL) {
            if ((p == line || isspace((unsigned char)p[-1]))
            &&  (p[len] == '\0' || isspace((unsigned char)p[len]))) {
                /* remove the word */
                memmove(p, p + len, strlen(p + len) + 1);
            } else {
                p += len;
            }
        }
        /* squeeze sequences of spaces as a single space */
        for (p = q = line + 1; *p; p++) {
            if (*p != ' ' || p[-1] != ' ')
                *q++ = *p;
        }
        *q = '\0';
        fputs(line, stdout);
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM