[英]how to use fgets instead of sscanf in c?
我是 c 的新手(然后我不能很好地理解互聯網答案),我正在嘗試使用 fgets,因為我注意到 sscanf 只選擇字符串的第一個單詞。 所以,我有一個這樣的代碼。 如果我的輸入是(例如): char line[100] = "My favourite animal is cat";
. 我用 sscanf 編寫了這段代碼。
char fav_animal[10];
sscanf(line,"My favourite animal is %s",fav_animal);
它適用於一個單詞,但我想使用 fgets,因為在我的程序中,用戶可以插入多個單詞。 所以,我想知道用 fgets 編寫的代碼的等價物是什么。
function fgets
對於將用戶輸入的一行作為字符串讀取非常有用。 但是,如果您已經有一個字符串並且想要解析它,那么fgets
就沒有用了。
如果你有一個字符串
char line[100] = "My favourite animal is cat";
並想將"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 );
}
這個程序有以下output:
The content of fav_animal is: cat
如果動物的名字由幾個單詞組成,這也將起作用。 例如,如果我改變
char line[] = "My favourite animal is cat";
至
char line[] = "My favourite animal is pit bull";
那么程序將有以下output:
The content of fav_animal is: pit bull
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.