Hey guyy , using getline allows us to read a file line by line. but is it possible to use getline to read individual words in a line? For example.

My name is John.

Using getline will read the entire line...

int main (){

       string templine;
       ifstream myfile("test.txt");
       getline(myfile , templine);

But is it possible to use getline and assigning each word to a string so it can be used later on? or perhaps using cin...

int main (){

       string templine;
       ifstream myfile("data.txt");
     string r , t , b , c , d ; 

       myfile >> r >>  t >> b >> c ;

is using cin the only way to assign each word or is there another way?

I would get the whole line and then split it at the spaces.

This is a pretty fancy way I found, but it works:

#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>

int main(int argc, char *argv[])
  std::string sentence = "hello world test 1 2 3";
  std::istringstream iss(sentence);
  std::vector<std::string> words;
             std::back_inserter<std::vector<std::string> >(words));
  for(unsigned int i = 0; i < words.size(); i++)
    std::cout << words[i] << std::endl;
  return 0;


the simplest way i know to get every word by itself from input would be

vector<string> words;
string temp;
while(getline(cin, temp, ' ')
This article has been dead for over six months. Start a new discussion instead.