Computer Science Canada

getchar() Help

Author:  crossley7 [ Thu Oct 27, 2011 9:52 pm ]
Post subject:  getchar() Help

Hey after seeing what the issues with this past dwite's first question, I am just wondering if anyone would have an easy way of reading \r\n characters with getline() in a way that doesn't cause it to read through twice and ideally not have to check if string length is 0 when reading in.

Either that or dwite should just use \n newline characters to be nice to those who wish to use getline() for similar types of problems. Razz

Author:  Tony [ Thu Oct 27, 2011 10:00 pm ]
Post subject:  Re: getchar() Help

crossley7 @ Thu Oct 27, 2011 9:52 pm wrote:
Either that or dwite should just use \n newline characters to be nice to those who wish to use getline() for similar types of problems. Razz

That doesn't really help. If you assume \n then someone else assumes \r\n. We'd just be shifting the problem to the other group of users.

We are currently investigating compilation flags and other compilers to deal with the issue though, as we've been discussing at http://compsci.ca/v3/viewtopic.php?t=29545

Author:  S_Grimm [ Mon Oct 31, 2011 8:27 am ]
Post subject:  Re: getchar() Help

code:


#include <iostream>
#include <fstream>
#include <string>
#include <locale>
#include <map>
#include <vector>
#include <crtdbg.h>
using namespace std;

int main(int argc, char *argv[])
{
        if (argc != 3)
        {
                cout << "Invalid Number of parameters. " << endl << "Input paramaters are [input file name] [output file name]" << endl;
                return EXIT_FAILURE;
        }

        vector<string> args;
        for( int i = 0; i < argc; ++i )
        {
                args.push_back( argv[i] );
        }

        ifstream inputFile (args[1]);
       
        if (!inputFile)
        {
                cout << "File " << args[1] << " could not be opened for reading" << endl;
                return EXIT_FAILURE;
        }
        ofstream outputFile (args[2]);

        if (!outputFile.is_open())
        {
                cout << "Unable to open or create " << args[3] << endl;
                return EXIT_FAILURE;
        }

        string x = "";

        while(inputFile >> x)
//do stuff with the string
//then output it

        if (inputFile.is_open())
                inputFile.close();
        if (outputFile.is_open())
                outputFile.close();
}


This way reads in a string or character or whatever "x" is assigned to, as long as it is streamable. It doesn't duplicate \n and keeps the original formatting of the input file.


: