Reading from file

A function takes a word from a list, counts how many letters it contains and print it out like this:

5 qatar
3 qua
5 quack
7 quacked.

Now I have a textfile for each letter in the alphabet and the function only works with the smaller files. If I use the file with a:s I only get this:
-1
-1
-1
And the program doesnt stop.
So, my problem is, how do I get it to work with the larger files?


AWord.open("TheA.txt");

while(!AWord.eof())
{
CountLetters = 0;

AWord.getline(PickedWord,18);

CountLetters = (AWord.gcount())-1;

cout << CountLetters << " " << PickedWord << endl;

}
Give more of the code please?
This is what I wrote to see if it worked. If I can make it work it will be a part of another program. I am using codeblocks IDE in Linux Lubuntu.

#include <iostream>
#include<fstream>

using namespace std;

void WhatSize();

int main()
{
WhatSize();
}

void WhatSize()
{
char PickedWord[18];
int CountLetters;

ifstream AWord;

AWord.open("TheA.txt");

while(!AWord.eof())
{
CountLetters = 0;

AWord.getline(PickedWord,18);

CountLetters = (AWord.gcount())-1;

cout << CountLetters << " " << PickedWord << endl;

}
}
Last edited on
Try using strlen for calculating the length of the string:
http://www.cplusplus.com/reference/cstring/strlen/
Try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <fstream>

int main()
{
	std::string line;
	std::ifstream ifs("words.txt");
	if(!ifs.is_open()) return 1;
	while(ifs)
	{
		std::getline(ifs, line);
		std::cout << line.length() << " " << line << "\n";
	}
	return 0;
}
I couldn't get strlen to work. Maybe i would have to restructure the code from scratch to make it work with strlen.

I tried your suggestion, Megatron O, and that worked.

Many thanks to both of you.
Topic archived. No new replies allowed.