0

...for spaces!
This is another thing where I beat the code into submission.
I just want someone to tell me if this is "good programming practice"-
or have i gone off on a tangent.
Is the use of the member access operator OK?

All this program does is take a text file and strip the spaces out

// this will open a file , read all the characters
// and display only letters and punctuation

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

int main()
{    
    cout << "Enter a filename: ";
    char filename[80];
    cin >> filename;
    ifstream file(filename);
    if (!file)
        
    {    
        cout << "File doesn't exist!" << endl;
        
    }
    else 
        if (file)
        {
            
        char ch;

        while (file.get(ch)!=0 )
    
        {    
        if (ch ==' ')
        
        file.get(ch).ignore(1,' ');
        else        
            cout << ch;
        }
        }        
            file.close();
            
        
    return 0;
}
2
Contributors
1
Reply
2
Views
10 Years
Discussion Span
Last Post by WaltP
0

...for spaces!
This is another thing where I beat the code into submission.
I just want someone to tell me if this is "good programming practice"-
or have i gone off on a tangent.
Is the use of the member access operator OK?

All this program does is take a text file and strip the spaces out

I would do it almost like that, but not quite. I'd make the loop simpler, among other things:

// this will open a file , read all the characters
// and display only letters and punctuation

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

int main()
{    
    cout << "Enter a filename: ";
    char filename[80];
    cin >> filename;
    ifstream file(filename);
    if (!file)
        
    {    
////    cout << "File doesn't exist!" << endl;
         cout << "File was not opened!" << endl; // could be a different reason
    }
    else 
////    if (file)       // you already know the file opened
    {
        char ch;
        while (file.get(ch) != 0 )
        {    
            if (ch !=' ')
            {
                cout << ch;
            }
        }
        file.close();
    }
    return 0;
}
This topic has been dead for over six months. 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.