0

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;
}
---------------------

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by qk00001
0

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;
}

Edited by sfuo: formatting

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.