fstream

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
joymar4
New poster
Posts: 1
Joined: Wed Mar 14, 2012 4:05 pm

fstream

Post by joymar4 » Wed Mar 14, 2012 4:18 pm

How can i put all words in a variable from textfile using fstream.

example
this is a sentence. ---------> i will store all of these words "this,is,a,sentence" in a variable.

Code: Select all

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
     // i dont know what to put in here so it will store in every variable or array????
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

help TT

brianfry713
Guru
Posts: 5947
Joined: Thu Sep 01, 2011 9:09 am
Location: San Jose, CA, USA

Re: fstream

Post by brianfry713 » Thu Mar 15, 2012 11:55 pm

Code: Select all

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main () {
  string s;
  vector<string> v;
  vector<string>::iterator it;
  ifstream myfile ("example.txt", ifstream::in);
  if (myfile.is_open())
    {
      while ( myfile.good() )
        {
	  // i dont know what to put in here so it will store in every variable or array????
	  if(myfile >> s)
	    v.push_back(s);
        }
      myfile.close();
    }
  else cout << "Unable to open file";

  for(it=v.begin();it!=v.end();it++)
    cout << *it << " ";
  cout << endl;
  
  return 0;
}
Check input and AC output for thousands of problems on uDebug!

Post Reply

Return to “C++”