【问题标题】:How to have multiple word input using sscanf?如何使用 sscanf 输入多个单词?
【发布时间】:2021-12-28 00:54:52
【问题描述】:

说我有:

char string[20][12];
string = "abcde bagfghabc cdfaga dnac eafagac cnaacaacaf"

我想使用 sscanf 使第一个、第三个和第一个单词在一个数组中,而其他单词在另一个数组中。所以每2个字。 (12 是最大字长) 我试过做

char odd[3][12];
char even[3][12];
int i = 0; 
while (i < 3) { 
   sscanf(string[i], odd[i], even[i]);
   i++;
}

非常感谢。

【问题讨论】:

  • 如果string是一个多维字符数组,那么你不能做string = "a b c d e f"。你也不能用这样一个字符串字面量来初始化它,因为这只能用一维数组来实现。
  • 我编辑了它希望它更清晰。

标签: c scanf


【解决方案1】:

您正在尝试使用sscanf 解决问题。但是,此函数需要一个格式字符串作为第二个参数,而您似乎没有传递一个。

此外,在循环中调用sscanf 时,在每次循环迭代中从字符串的开头开始解析是没有意义的。相反,您想告诉它在它已经解析的单词的末尾继续解析。因此,您必须引入一个额外的指针变量来跟踪已经解析了多少字符串,并且您必须在每次调用 sscanf 后提前该指针。为此,使用 sscanf %n 格式说明符很有用。

这是一个如上所述的解决方案:

#include <stdio.h>

#define MAX_WORD_PAIRS 3
#define MAX_WORD_SIZE 12

int main( void )
{
    char  odd[MAX_WORD_PAIRS][MAX_WORD_SIZE];
    char even[MAX_WORD_PAIRS][MAX_WORD_SIZE];

    char string[] = "word1 word2 word3 word4 word5 word6";

    char *p = string;
    int num_pairs;
    int characters_read;

    //attempt to read one pair of words in every loop iteration
    for ( num_pairs = 0; num_pairs < MAX_WORD_PAIRS; num_pairs++ )
    {
        //attempt to read a new pair of words
        if ( sscanf( p, "%s%s%n", odd[num_pairs], even[num_pairs], &characters_read ) != 2 )
            break;

        //advance pointer past the parsed area
        p += characters_read;
    }

    //processing is complete, so we can now print the results

    //print odd words
    printf( "odd words:\n" );
    for ( int i = 0; i < num_pairs; i++ )
    {
        printf( "%s\n", odd[i] );
    }

    printf( "\n" );

    //print even words
    printf( "even words:\n" );
    for ( int i = 0; i < num_pairs; i++ )
    {
        printf( "%s\n", even[i] );
    }
}

这个程序有以下输出:

odd words:
word1
word3
word5

even words:
word2
word4
word6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多