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.


Test.txt
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::copy(std::istream_iterator<std::string>(iss),
             std::istream_iterator<std::string>(),
             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;
}

Dave

Sure. See this.

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

vector<string> words;
string temp;
while(getline(cin, temp, ' ')
       words.push_back(temp);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.