# How to find the number of words from the a text file

Page 1 of 1

## 2 Replies - 285 Views - Last Post: 07 October 2016 - 01:59 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=397789&amp;s=83c72ab904fc421c62d5d38520350e52&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 hphan1997

• New D.I.C Head

Reputation: 0
• Posts: 6
• Joined: 07-October 16

# How to find the number of words from the a text file

Posted 07 October 2016 - 01:14 PM

```void tokenStats(ifstream& in, ostream& out) {
in.open("problem18Text.txt");

int integers;
int integers2;
double doubles;
double doubles2;
string word;
int sumIntegers = 0;
double sumInDoubles = 0.0;
int token = 0;

while (in >> integers >> doubles >> integers2 >> word >> word >> doubles2) {
sumIntegers = integers + integers2;
sumInDoubles = doubles + doubles2;
token++;

}
out << "integers: " << sumIntegers << endl;
out << "real numbers: " << sumInDoubles << endl;
out << "total tokens: " << token << endl;
```

Quote

"problem18Text.txt" file:
3 3.14 10 squid 10.x 6.0

Quote

My output:
integers: 13
real numbers: 9.14
total tokens: 1
Press any key to continue . . .

Quote

The correct output:
integers: 13
real numbers: 9.14
total tokens: 6
Press any key to continue . . .

I get everything correct except the tokens which are the number of words in each line. There are 6 tokens from problem18Text.txt file. However I only get one...Any suggestions?

Is This A Good Question/Topic? 0

## Replies To: How to find the number of words from the a text file

### #2 jimblumberg

Reputation: 5334
• Posts: 16,609
• Joined: 25-December 09

## Re: How to find the number of words from the a text file

Posted 07 October 2016 - 01:22 PM

You're reading multiple "tokens" but only increasing tokens by one. Also if your file has the "tokens" in a different order your program will fail.

Try something like: "3.14 3 10 squid 10.x 6.0" and see what happens.

Jim

### #3 hphan1997

• New D.I.C Head

Reputation: 0
• Posts: 6
• Joined: 07-October 16

## Re: How to find the number of words from the a text file

Posted 07 October 2016 - 01:59 PM

jimblumberg, on 07 October 2016 - 01:22 PM, said:

You're reading multiple "tokens" but only increasing tokens by one. Also if your file has the "tokens" in a different order your program will fail.

Try something like: "3.14 3 10 squid 10.x 6.0" and see what happens.

Jim

I'm not allowed to change the textfile. I have to get it right without changing the text file.