On Nov 3, 2:11*pm, Pali <mahana...@gmail.com> wrote:
> I need to read a line from a text file by character by character. Then
> assign the words in that line, which are separated by spaces in to
> separate strings. Pl. tell me how to code this from c++.
hi, the following program reads a file, m.cpp, a word at a time,
pushes that into a container (such as vector), sorts the container,
and finally prints each word.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
int main(int argc, char* argv[])
{
using namespace std;
ifstream in("m.cpp");
if(!in) {
cerr << "can't open file!";
return -1;
}
// file ok
vector<string> vec;
string word;
while(in >> word)
vec.push_back(word);
in.close();
// sort words
sort(vec.begin(), vec.end());
// print
typedef vector<string>::const_iterator VCI;
for(VCI i = vec.begin(); i != vec.end(); ++i)
cout << *i << endl;
return 0;
}
|