逐字读取字符数组,无需字符串函数

Read char array word by word without string functions

本文关键字:字符串 函数 数组 读取 字符      更新时间:2023-10-16

我有包含一些单词的char数组words,我必须在不使用字符串库的情况下读取其中的所有单词(不能使用strtok(。这是我所拥有的:

int wordsCount = 0;
for (int i = 0; words[i] != ''; i++) {
    if (words[i] == ' ')
        wordsCount++;
}
wordsCount++;
char word[30];
for (int i = 0; i < wordsCount; i++) {
    sscanf(words, "%s", word);
}


该代码只读取第一个单词,我想我必须向sscanf添加一些东西,但我不知道是什么,或者有没有其他方法来实现我的目标?

假设您希望继续使用 C I/O API,您可以使用 std::scanf 的内置空格跳过功能:

int main() {
    char const *str = "She sells seashells by the seashore";
    char word[30];
    unsigned wordLength;
    for(; std::sscanf(str, " %29s%n", word, &wordLength) == 1; str += wordLength)
        std::printf("Read word: "%s"n", word);
}

输出:

读字:"她"阅读单词:"出售"阅读单词:"贝壳"读字:"由"读字:"的"读字:"海边">

当然,你应该比我没有更好地检查错误;)

现场演示

读取以下内容后,您需要递增指针:

char word[30];
int offset = 0;
for (int i = 0; i < wordsCount; i++) {
    sscanf(words, "%s", word);
    offset += strlen(word) + 1;
}

* 如果您words包含连续空格,上面的代码将无法按预期工作。您需要考虑如何修复偏移量。

顺便说一句,使用std::string streamstd::string会更容易,更安全。

std::istringstream iss (words);
std::string word;
while(iss >> word) do_something(word);