Bya413
Bya413

Reputation: 133

How to read a .txt file character by character without <iostream>?

I have an assignment that requires us to reformat a text file that is given to us. The program is ran using the cmd, and is given two command parameters; a number, and the name of a text file. My job is to write a function that will format the text file, and display it in a specific format. However, I'm having a very very hard time even getting started.

I am ONLY allowed to edit this function, and only allowed to add code between these two brackets;

void typeset (int maxWidth, istream& documentIn)
{

}

I am completely lost on what to do. I've spent the past hour and a half trying various things, but none of them work. I'm not sure how the syntax works. Above the 'void typeset', is more code, but I am not allowed to alter it. Here's what's at the beginning of the .cpp

#include "typeset.h"
#include <string>
#include <sstream>
#include <iostream>
using namespace std;

I've got no idea how to do the bit where I 'read' the text file. What I'd like to do is have a loop that continuously reads characters until there's a space, saves that string of characters as a word, and continues to do so until it reaches the end of the file. Everything I've found uses something like std::ifstream, which doesn't seem to work. Thank you for your time.

Upvotes: 0

Views: 394

Answers (1)

john
john

Reputation: 87957

The problem seem to be a lack of understanding of how streams work. You are not supposed to create your own ifstream, you are supposed to use the istream& supplied to the function

Write some code like this to read the document one character at a time

void typeset (int maxWidth, istream& documentIn)
{
    char ch;
    while (documentIn.get(ch))
    {
        ...
    }
}

To me your confusion seems to characterise someone who just looks on the internet for something close to what they want to do. At some point you have to get a more fundamental understanding of C++, so that you can understand code and write original code, instead of just copying and modifying code. You're only going to get that by reading a textbook, which explains the principles behind C++.

In this case the principle is that all the different input streams derive from istream so input from any kind of stream can be done with an istream.

Upvotes: 2

Related Questions