Hi people, I am trying to read a text file and count each words length.

I have got these 2 things working, but I can't write the wordLength into text file.

anyone can help me out. thanks a lot~~

there is the text file like:
-------------
absent
absolute
absolutely
absorb
abstract
------------

then I need to make the text file like

-----------
absent,5
absolute,8
absolutely,10
absorb ,6
abstract,8
------------

here is the code:
---------------------
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{
string line;
ifstream infile("words.txt");
while ( getline(infile, line) )
{
cout << line<<",";
string str(line);
cout <<str.length() <<endl;
}
return 0;
}
---------------------

Recommended Answers

All 2 Replies

Just need to make a text file called textin.txt with your words and put it in the same directory as your .exe file.

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

int main()
{
    string line; //to hold the lines read from textin.txt
    ifstream in("textin.txt");
    ofstream out("textout.txt");
    while ( getline(in, line) )
        out << line << ", " << line.length() << endl; //output the word and the length of the word
    out.close(); //after the loop close both files
    in.close();
    return 0;
}

Many thank to sfuo. you are star!!!

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.