拆分字符串后如何访问单个单词?

tho*_*ald 3 c++

std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token[0] << "\n";
Run Code Online (Sandbox Code Playgroud)

这是打印单个字母.我如何得到完整的单词?

更新以添加:

我需要将它们作为执行此类操作的单词进行访问...

if (word[0] == "something")
   do_this();
else
   do_that();
Run Code Online (Sandbox Code Playgroud)

Fre*_*Foo 5

std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token << "\n";
Run Code Online (Sandbox Code Playgroud)

存储所有令牌:

std::vector<std::string> tokens;
while (getline(iss, token, ' '))
    tokens.push_back(token);
Run Code Online (Sandbox Code Playgroud)

要不就:

std::vector<std::string> tokens;
while (iss >> token)
    tokens.push_back(token);
Run Code Online (Sandbox Code Playgroud)

现在tokens[i]i第一个令牌.

  • 如果你这样做,你也可以使用`iss >> token`,它也会得到由其他空白字符分隔的单词. (2认同)