使用sscan()拆分白色间隔字符串

Splitting a white-spaced string using sscanf()

本文关键字:字符串 白色 拆分 sscan 使用      更新时间:2023-10-16

我正在尝试使用sscanf()拆分一个带有空格的长字符串。

例如:我需要拆分这个

We're a happy family

进入

We're
a
happy
family

我尝试了以下方法

char X[10000];
fgets(X, sizeof(X) - 1, stdin); // Reads the long string
if(X[strlen(X) - 1] == 'n') X[strlen(X) - 1] = ''; // Remove trailing newline
char token[1000];
while(sscanf(X, "%s", token) != EOF) {
    printf("%s | %sn", token, X);
}

前一个代码进入无限循环输出We're | We're a happy family

我尝试用C++istringstream替换sscanf(),效果很好。

是什么让X保持它的价值?难道它不应该像正常流一样从缓冲区中删除吗?

sscanf()确实存储了关于它以前读取的缓冲区的信息,并且将始终从传递给它的地址(缓冲区(开始。一个可能的解决方案是使用%n格式说明符来记录最后一个sscanf()停止的位置,并将X + pos作为第一个参数传递给sscanf()。例如:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    const char* X = "hello again there";
    char token[1000];
    int current_pos = 0;
    int pos = 0;
    while (1 == sscanf(X + current_pos, "%999s%n", token, &pos))
    {
        current_pos += pos;
        printf("%s | %sn", token, X + current_pos);
    }
    return 0;
}

请参阅演示http://ideone.com/XBDTWm。

或者只使用istringstreamstd::string:

std::istringstream in("hello there again");
std::string token;
while (in >> token) std::cout << token << 'n';