简体   繁体   English

如何在 c 中使用 fgets 而不是 sscanf?

[英]how to use fgets instead of sscanf in c?

i'm very new in c (and then i can't understand internet answers so well) and i'm triyng to use fgets, since i notices that sscanf picks only the first word of a string.我是 c 的新手(然后我不能很好地理解互联网答案),我正在尝试使用 fgets,因为我注意到 sscanf 只选择字符串的第一个单词。 so, i have a code like that.所以,我有一个这样的代码。 if my input is (for example): char line[100] = "My favourite animal is cat";如果我的输入是(例如): char line[100] = "My favourite animal is cat"; . . i wrote this code with sscanf.我用 sscanf 编写了这段代码。

char fav_animal[10];

sscanf(line,"My favourite animal is %s",fav_animal);

And it works well with one word, but i want to use fgets because in my program an user can insert multiple words.它适用于一个单词,但我想使用 fgets,因为在我的程序中,用户可以插入多个单词。 So, i wanted to know what is the equivalent, written with the fgets, of the code written up.所以,我想知道用 fgets 编写的代码的等价物是什么。

The function fgets is useful for reading one line of user input as a string. function fgets对于将用户输入的一行作为字符串读取非常有用。 However, if you already have a string and want to parse that, then fgets is useless.但是,如果您已经有一个字符串并且想要解析它,那么fgets就没有用了。

If you have a string如果你有一个字符串

char line[100] = "My favourite animal is cat";

and want to copy everything after "My favorite animal is" to another string fav_animal , then you can use the following code:并想将"My favorite animal is"之后的所有内容复制到另一个字符串fav_animal ,那么您可以使用以下代码:

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

int main( void )
{
    char line[] = "My favourite animal is cat";

    char fav_animal[10];
    char start[] = "My favourite animal is ";
    size_t start_len = strlen( start );

    //make sure that line starts with "My favourite animal is "
    if ( strncmp( line, start, start_len ) != 0 )
    {
        printf( "Error, line does not start with expected string.\n" );
        exit( EXIT_FAILURE );
    }

    //copy remainder of line into fav_animal
    snprintf( fav_animal, sizeof fav_animal, "%s", line + start_len );

    //print fav_animal
    printf( "The content of fav_animal is: %s\n", fav_animal );
}

This program has the following output:这个程序有以下output:

The content of fav_animal is: cat

This will also work if the animal's name consists of several words.如果动物的名字由几个单词组成,这也将起作用。 For example, if I change例如,如果我改变

char line[] = "My favourite animal is cat";

to

char line[] = "My favourite animal is pit bull";

then the program will have the following output:那么程序将有以下output:

The content of fav_animal is: pit bull

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

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