繁体   English   中英

C使用fgets获取具有未知长度的空格的字符串

[英]C get string with spaces, of unknown length, with fgets

我有一个包含1行的文件,在Linux上它默认以换行结束

one two three four

和一个类似的

one five six four

保证两者之间的两个词永远不会是“四”。 我写了以下内容,希望将“two three”和“five six”分配给变量,如此代码中所示。

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

bool getwords(FILE *example)
{
    bool result = 0;
    char *words;
        if(fscanf(example, "one %s four\n", words) == 1)
        {
            printf("captured words are %s\n", words);
            if(words == "two three"
            || words == "five six")
            {
                puts("example words found");
            }
            else
            {
                puts("unexpected words found");
            }
            result = 1; //so that we know this succeeded, in some way
        }
    return result;
}

int main(int argc, char * argv[])
{
    if(argc != 2)
    {
        exit(0);
    }
    FILE *example;
    example = fopen(argv[1],"r");
    printf("%x\n", getwords(example)); //we want to know the return value, hex is okay
    fclose(example);
    return 0;
}

问题是,这将打印“捕获的单词是”,然后只在字符串中预期两个中的第一个单词。 这应该支持文件,其中单词“one”和“four”之间可能有比2更多的单词。 如何更改我的代码,以获取字符串中第一个和最后一个单词之间的所有单词?

您的代码在当前状态中存在大量错误。

首先,你需要分配char *words; 该语句当前仅声明指向字符串的指针,并且不创建该字符串。 快速修复将是char words[121];

另外,限制scanf的捕获范围以匹配具有scanf("one %120s four", words);words长度scanf("one %120s four", words); 但这不会捕获这两个单词,因为%s只搜索一个单词。 一种解决方案是扫描每个单词fscanf("one %120s %120s four", first_word, second_word); 然后逐一比较。

其次,您无法使用==运算符比较两个字符串。 ==比较变量的值, words只是一个指针。 一个修复方法是使用strcmp(words, "two three") == 0你写的是words == "two three"

已经使用您的代码并将其修改为与Eclipse / Microsoft C编译器一起使用。 但是,总的来说,我认为我保持原始意图完好无损(?)。

请查看并注意细微的变化。 我知道这可能是你用C编写的第一个程序之一,所以说最后你会得知非学生程序不是用这种方式编写的。

最后,尽管其他人说, fscan在按预期使用时没有任何问题。

#include <stdio.h>
#include <stdlib.h>

int getwords(FILE *example)
{
    int result = 0;
    char word1[20];  //<< deprecated, learn and use malloc
    char word2[20];  //<< works for first pgm, etc.

    if( fscanf(example, "one %s %s four", word1, word2) == 2)
        {
            printf("captured words are: %s %s\n", word1, word2);

            if ((!strcmp(word1, "two") && !strcmp(word2,"three")) ||
                (!strcmp(word1, "five") && !strcmp(word2, "six")))
            {
                printf("example words found\n");
            }
            else
            {
                printf("unexpected words found\n");
            }
            result = 1; //so that we know this succeeded, in some way
        }
    return result;
}

main(int argc, char *argv[])
{

    FILE *example;

    if(argc != 2) {exit(0);}

    example = fopen(argv[1],"r");
    // it is a good practice to test example to see if the file was opened

    printf("return value=%x\n", getwords(example)); //we want to know the return value, hex is okay

    fclose(example);

    return 0;
}

暂无
暂无

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

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