我在使用strtok()函数时遇到了一些麻烦。我想要做的是从键盘上抓一个句子,然后为句子中的每个空格创建标记,然后最后打印由空格分隔的每个单词。我目前的输出是空白我有一种感觉与我的分隔符有关但我不确定,任何反馈都会很好谢谢!
键盘输入示例:
The sky is really cool
输出示例:
the
sky
is
really
cool
到目前为止我的代码
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
int main(){
char sent[99];
int length = strlen(sent);
cout << "Enter a Sentence" << endl;
cin.getline(sent,99);
char* tok = strtok(sent," ");
int i = 0;
while (i<=length)
{
tok = strtok(NULL, " ");
cout << tok;
i++;
}
system("pause");
}
到目前为止的输出
Enter a Sentence
the sky is really cool
Press any key to continue . . .
答案 0 :(得分:1)
您根本不需要length
,因为strtok()
如果找不到更多的分隔符,将返回空指针:
char* token = strtok(sent," ");
while (token != NULL) {
std::cout << token << '\n';
token = strtok(NULL, " ");
}
由于这是标记的C ++,您还可以将istringstream
与std::string
一起使用:
std::istreamstream is(sent);
std::string word;
while (is >> word) {
std::cout << word << '\n';
}
答案 1 :(得分:1)
您的代码中需要修复几个问题:
while
循环中使用的逻辑不正确。这是一个简化的main
:
int main(){
char sent[99];
cout << "Enter a Sentence" << endl;
cin.getline(sent,99);
char* tok = strtok(sent," ");
while (tok != NULL) // Correct logic to use to stop looping.
{
cout << tok << endl; // Print the current token before getting the next token.
tok = strtok(NULL, " ");
}
}