How to access individual words after line splitting?

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

std::cout << token[0] << "\n";

It prints single letters. How to get full words?

Updated to add:

I need to access them like words in order to do something like this ...

if (word[0] == "something")
   do_this();
else
   do_that();
+3
source share
5 answers
std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token << "\n";

To save all markers:

std::vector<std::string> tokens;
while (getline(iss, token, ' '))
    tokens.push_back(token);

or simply:

std::vector<std::string> tokens;
while (iss >> token)
    tokens.push_back(token);

Now tokens[i]this is the ith token .

+5
source

First you need to determine what the word does .

If this is whitespace , iss >> tokenthis is the default option:

std::string line("This is a sentence.");
std::istringstream iss(line);

std::vector<std::string> words. 
std::string token;
while(iss >> token)
  words.push_back(token);

It should find

This
is
a
sentence.

like words.

If this is something more complex than spaces, you will have to write your own lexer.

+2
source

- - , . [0], , String.

+1
source

Just print the token and get getline again.

0
source

You have defined tokenhow std::string, which uses the index operator []to return a single character. To display the entire string, do not use the index operator.

0
source

Source: https://habr.com/ru/post/1777726/


All Articles