Word Counter Problem

So I've been working with XCode as my compiler for sometime with no issues.
The problem I am working on is:

-------------------------------------------
Write a program that prints out the number of words in a file of text. We will define a word to be any sequence of non-whitespace characters. So "hi&there...mom" would be considered a single word. Solve this problem by using a string variable into which you input each word as a string.
-------------------------------------------

I've written my own code as well as used code that I've found on here to try and make this work, however something keeps happening that makes it impossible. I'm not sure if it's me, XCode, or some stupid setting. The source code that I've seen work from here is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 // This program counts the number of words in files selected by the user.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main ( )
{
    ifstream inputfile;
    string filename;
    string words;
    
    //Get the filename from the user.
    cout << "Enter the filename: ";
    cin >> filename;
    
    //Open the input file.
    inputfile.open(filename.c_str());
    
    //If the file succesfully opened, process it.
    if (inputfile)
    {
        while (inputfile >> words)
            cout << words << endl;
        
        //Clost the file.
        inputfile.close();
    }
    else
    {
        //Display an error message.
        cout << "Error opening the file.\n";
    }
    
    return 0;
}


The user had an output of (with the exact same file):
"OUTPUT:
Enter the filename: fileone.txt
This
&%file
should!!,...
have
exactly
7
words.
Program ended with exit code: 0"

However, when I input the same code with the same file, my output is:
Enter the filename: Words1.txt
{\rtf1\ansi\ansicpg1252\cocoartf1404\cocoasubrtf470
{\fonttbl\f0\fmodern\fcharset0
Courier;}
{\colortbl;\red255\green255\blue255;\red0\green0\blue0;}
\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\deftab720
\pard\pardeftab720\sl280\partightenfactor0
\f0\fs24
\cf0
\expnd0\expndtw0\kerning0
This
&%file\cf2
\outl0\strokewidth0
\strokec2
\cf0
\outl0\strokewidth0
should!!,...
\
\
\
have
exactly
7
words.\
}
Program ended with exit code: 0


What is this and why is this happening?
Last edited on
I would think that 'Words1.txt' is a rtf text:

https://en.wikipedia.org/wiki/Rich_Text_Format
I've gone back and forth converting with .txt and .rtf, both yield the same output
Hello deadmittens,

Since no one has said it yet, you need to delete the "Words1.txt" file and start over. If yo are using Windows notepad will work to create simple .txt file. I think it would be easier to create a new file than try to fix the one you have.

Hope that helps,

Andy
Topic archived. No new replies allowed.