gpt4 book ai didi

c++ - 不使用字符串函数逐字读取字符数组

转载 作者:行者123 更新时间:2023-11-30 03:31:40 25 4
gpt4 key购买 nike

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

int wordsCount = 0;

for (int i = 0; words[i] != '\0'; 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);
}

输出:

Read word: "She"Read word: "sells"Read word: "seashells"Read word: "by"Read word: "the"Read word: "seashore"

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

Live demo

关于c++ - 不使用字符串函数逐字读取字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44043731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com