c++ reading characters in from a file char by char using only char arrays[]












0














I am working on an assignment for my c++ class, and I am pretty close to solving my problem. At this point, I am getting output that is ALMOST what I was expecting, so I suspect that I may be misunderstanding a core concept of this problem. The part of my assignment I am working on now is to get a file name from the user, read in that file, and then display that file while replacing key characters. For example, :!, will be replaced with 'n' to make a new line. I am only allowed to use iostream and fstream, and all text must be handled with char arrays. In my current output, I am getting an extra space on the third line, and I do not understand how it is getting there. Because of this, I think I may have the logic wrong in my head, and was wondering if any more experienced programmers could explain where I am going wrong. Am I going in the right direction?



here is the text file I am using as practice: 1.txt



Type, type, type away :!
compile.
Run.
Hip hip hooray! :! No errors today! :!


This is the expected output of the same file: 1.txt



Type, type, type away
compile. Run. Hip hip hooray!
No errors today!


this is the output that I am getting



Type, type, type away
compile. Run. Hip hip hooray!
No errors today! <<-------- extra space at the beginning!


I will paste my code below, feel free to critique it in any way.



#include <iostream>
#include <fstream>
using namespace std;
#define MAX 1024 // this is the maximum allowed number of char in a file.
// is it a bad idea to define it as a constant?

int main()
{
char fileName[256];
char data[MAX];
int readFile(char fileName,char data);
void display(char data, int counter);
fstream file;

cout << "File Name: ";
cin >> fileName;

int counter = readFile(fileName, data);
display(data, counter);

return 0;
}

int readFile(char fileName, char data)
{
ifstream file;
file.open(fileName);

int count = 0;
while(file.get(data[count]) && count < MAX)
{
count++;
}
file.close();
return count;
}

void display(char data, int counter)
{
char formatText(char data, int count);
for(int i = 0; i < counter; i++)
{
if(data[i] == 'n') // I added this if statment in because the newline
{ // from the file was getting read, AND the :! was
data[i] = ''; // becoming n, printing out TWO new lines!
}

}
for(int i = 0; i < counter; i++)
{
formatText(data, i);

if(data[i] != ':') // All tokens have a : before, So i dont want to
cout << data[i]; // print out the :'s.
}
}

char formatText(char data, int count)
{
if(data[count] == ':')
{
switch(data[count + 1]) // these are the three tokens I have been given,
{ // but it has to be expandable for more later.
case '!': data[count + 1] = 'n';
break;
case '<': data[count + 1] = '"';
break;
case '>': data[count + 1] = '"';
break;
}
}

}


I'm sorry if this has been answered in another post, I was unable to find (or possibly understand) the answer to my question. Thank you for your time and patience.










share|improve this question


















  • 2




    You should use constexpr instead of #define. It is less error-prone.
    – Fei Xiang
    Nov 20 at 5:12






  • 2




    It looks to me like the space you are complaining about should be there. It is in your input file (a space after the :!) hence unless your requirements were also to strip leading whitespace, I think your current output is correct.
    – Steven W. Klassen
    Nov 20 at 5:13










  • If the expected output is to condense/drop leading and trailing whitespace and extra whitepace between words, you'll best solve this with two flags: 1) one flag records that you've seen a space so that when you encounter a letter you first output a space, except when you are translating your special newline code or when: 2) another flag records that you've seen the first non-space character on the current line -- if that is not set, you never output any leading space.
    – paddy
    Nov 20 at 5:18












  • my teacher has a program that runs my version against hers with the same text file. In her version, it doesn't have that extra space, even though there is a space after the :! in the text file! hmm.... would it be possible for me to read in all characters ignoring white space, and then add them in correctly afterward in the display function? My teacher's program seems to be ignoring all white spaces except the ones that exist between words. God, I wish I could just use strings.
    – Liam Ihasz
    Nov 20 at 5:20










  • @paddy If I am only reading one char at a time, how can I know if the space I am reading is the first one in the line?
    – Liam Ihasz
    Nov 20 at 5:28
















0














I am working on an assignment for my c++ class, and I am pretty close to solving my problem. At this point, I am getting output that is ALMOST what I was expecting, so I suspect that I may be misunderstanding a core concept of this problem. The part of my assignment I am working on now is to get a file name from the user, read in that file, and then display that file while replacing key characters. For example, :!, will be replaced with 'n' to make a new line. I am only allowed to use iostream and fstream, and all text must be handled with char arrays. In my current output, I am getting an extra space on the third line, and I do not understand how it is getting there. Because of this, I think I may have the logic wrong in my head, and was wondering if any more experienced programmers could explain where I am going wrong. Am I going in the right direction?



here is the text file I am using as practice: 1.txt



Type, type, type away :!
compile.
Run.
Hip hip hooray! :! No errors today! :!


This is the expected output of the same file: 1.txt



Type, type, type away
compile. Run. Hip hip hooray!
No errors today!


this is the output that I am getting



Type, type, type away
compile. Run. Hip hip hooray!
No errors today! <<-------- extra space at the beginning!


I will paste my code below, feel free to critique it in any way.



#include <iostream>
#include <fstream>
using namespace std;
#define MAX 1024 // this is the maximum allowed number of char in a file.
// is it a bad idea to define it as a constant?

int main()
{
char fileName[256];
char data[MAX];
int readFile(char fileName,char data);
void display(char data, int counter);
fstream file;

cout << "File Name: ";
cin >> fileName;

int counter = readFile(fileName, data);
display(data, counter);

return 0;
}

int readFile(char fileName, char data)
{
ifstream file;
file.open(fileName);

int count = 0;
while(file.get(data[count]) && count < MAX)
{
count++;
}
file.close();
return count;
}

void display(char data, int counter)
{
char formatText(char data, int count);
for(int i = 0; i < counter; i++)
{
if(data[i] == 'n') // I added this if statment in because the newline
{ // from the file was getting read, AND the :! was
data[i] = ''; // becoming n, printing out TWO new lines!
}

}
for(int i = 0; i < counter; i++)
{
formatText(data, i);

if(data[i] != ':') // All tokens have a : before, So i dont want to
cout << data[i]; // print out the :'s.
}
}

char formatText(char data, int count)
{
if(data[count] == ':')
{
switch(data[count + 1]) // these are the three tokens I have been given,
{ // but it has to be expandable for more later.
case '!': data[count + 1] = 'n';
break;
case '<': data[count + 1] = '"';
break;
case '>': data[count + 1] = '"';
break;
}
}

}


I'm sorry if this has been answered in another post, I was unable to find (or possibly understand) the answer to my question. Thank you for your time and patience.










share|improve this question


















  • 2




    You should use constexpr instead of #define. It is less error-prone.
    – Fei Xiang
    Nov 20 at 5:12






  • 2




    It looks to me like the space you are complaining about should be there. It is in your input file (a space after the :!) hence unless your requirements were also to strip leading whitespace, I think your current output is correct.
    – Steven W. Klassen
    Nov 20 at 5:13










  • If the expected output is to condense/drop leading and trailing whitespace and extra whitepace between words, you'll best solve this with two flags: 1) one flag records that you've seen a space so that when you encounter a letter you first output a space, except when you are translating your special newline code or when: 2) another flag records that you've seen the first non-space character on the current line -- if that is not set, you never output any leading space.
    – paddy
    Nov 20 at 5:18












  • my teacher has a program that runs my version against hers with the same text file. In her version, it doesn't have that extra space, even though there is a space after the :! in the text file! hmm.... would it be possible for me to read in all characters ignoring white space, and then add them in correctly afterward in the display function? My teacher's program seems to be ignoring all white spaces except the ones that exist between words. God, I wish I could just use strings.
    – Liam Ihasz
    Nov 20 at 5:20










  • @paddy If I am only reading one char at a time, how can I know if the space I am reading is the first one in the line?
    – Liam Ihasz
    Nov 20 at 5:28














0












0








0







I am working on an assignment for my c++ class, and I am pretty close to solving my problem. At this point, I am getting output that is ALMOST what I was expecting, so I suspect that I may be misunderstanding a core concept of this problem. The part of my assignment I am working on now is to get a file name from the user, read in that file, and then display that file while replacing key characters. For example, :!, will be replaced with 'n' to make a new line. I am only allowed to use iostream and fstream, and all text must be handled with char arrays. In my current output, I am getting an extra space on the third line, and I do not understand how it is getting there. Because of this, I think I may have the logic wrong in my head, and was wondering if any more experienced programmers could explain where I am going wrong. Am I going in the right direction?



here is the text file I am using as practice: 1.txt



Type, type, type away :!
compile.
Run.
Hip hip hooray! :! No errors today! :!


This is the expected output of the same file: 1.txt



Type, type, type away
compile. Run. Hip hip hooray!
No errors today!


this is the output that I am getting



Type, type, type away
compile. Run. Hip hip hooray!
No errors today! <<-------- extra space at the beginning!


I will paste my code below, feel free to critique it in any way.



#include <iostream>
#include <fstream>
using namespace std;
#define MAX 1024 // this is the maximum allowed number of char in a file.
// is it a bad idea to define it as a constant?

int main()
{
char fileName[256];
char data[MAX];
int readFile(char fileName,char data);
void display(char data, int counter);
fstream file;

cout << "File Name: ";
cin >> fileName;

int counter = readFile(fileName, data);
display(data, counter);

return 0;
}

int readFile(char fileName, char data)
{
ifstream file;
file.open(fileName);

int count = 0;
while(file.get(data[count]) && count < MAX)
{
count++;
}
file.close();
return count;
}

void display(char data, int counter)
{
char formatText(char data, int count);
for(int i = 0; i < counter; i++)
{
if(data[i] == 'n') // I added this if statment in because the newline
{ // from the file was getting read, AND the :! was
data[i] = ''; // becoming n, printing out TWO new lines!
}

}
for(int i = 0; i < counter; i++)
{
formatText(data, i);

if(data[i] != ':') // All tokens have a : before, So i dont want to
cout << data[i]; // print out the :'s.
}
}

char formatText(char data, int count)
{
if(data[count] == ':')
{
switch(data[count + 1]) // these are the three tokens I have been given,
{ // but it has to be expandable for more later.
case '!': data[count + 1] = 'n';
break;
case '<': data[count + 1] = '"';
break;
case '>': data[count + 1] = '"';
break;
}
}

}


I'm sorry if this has been answered in another post, I was unable to find (or possibly understand) the answer to my question. Thank you for your time and patience.










share|improve this question













I am working on an assignment for my c++ class, and I am pretty close to solving my problem. At this point, I am getting output that is ALMOST what I was expecting, so I suspect that I may be misunderstanding a core concept of this problem. The part of my assignment I am working on now is to get a file name from the user, read in that file, and then display that file while replacing key characters. For example, :!, will be replaced with 'n' to make a new line. I am only allowed to use iostream and fstream, and all text must be handled with char arrays. In my current output, I am getting an extra space on the third line, and I do not understand how it is getting there. Because of this, I think I may have the logic wrong in my head, and was wondering if any more experienced programmers could explain where I am going wrong. Am I going in the right direction?



here is the text file I am using as practice: 1.txt



Type, type, type away :!
compile.
Run.
Hip hip hooray! :! No errors today! :!


This is the expected output of the same file: 1.txt



Type, type, type away
compile. Run. Hip hip hooray!
No errors today!


this is the output that I am getting



Type, type, type away
compile. Run. Hip hip hooray!
No errors today! <<-------- extra space at the beginning!


I will paste my code below, feel free to critique it in any way.



#include <iostream>
#include <fstream>
using namespace std;
#define MAX 1024 // this is the maximum allowed number of char in a file.
// is it a bad idea to define it as a constant?

int main()
{
char fileName[256];
char data[MAX];
int readFile(char fileName,char data);
void display(char data, int counter);
fstream file;

cout << "File Name: ";
cin >> fileName;

int counter = readFile(fileName, data);
display(data, counter);

return 0;
}

int readFile(char fileName, char data)
{
ifstream file;
file.open(fileName);

int count = 0;
while(file.get(data[count]) && count < MAX)
{
count++;
}
file.close();
return count;
}

void display(char data, int counter)
{
char formatText(char data, int count);
for(int i = 0; i < counter; i++)
{
if(data[i] == 'n') // I added this if statment in because the newline
{ // from the file was getting read, AND the :! was
data[i] = ''; // becoming n, printing out TWO new lines!
}

}
for(int i = 0; i < counter; i++)
{
formatText(data, i);

if(data[i] != ':') // All tokens have a : before, So i dont want to
cout << data[i]; // print out the :'s.
}
}

char formatText(char data, int count)
{
if(data[count] == ':')
{
switch(data[count + 1]) // these are the three tokens I have been given,
{ // but it has to be expandable for more later.
case '!': data[count + 1] = 'n';
break;
case '<': data[count + 1] = '"';
break;
case '>': data[count + 1] = '"';
break;
}
}

}


I'm sorry if this has been answered in another post, I was unable to find (or possibly understand) the answer to my question. Thank you for your time and patience.







c++ ifstream






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 at 5:08









Liam Ihasz

1




1








  • 2




    You should use constexpr instead of #define. It is less error-prone.
    – Fei Xiang
    Nov 20 at 5:12






  • 2




    It looks to me like the space you are complaining about should be there. It is in your input file (a space after the :!) hence unless your requirements were also to strip leading whitespace, I think your current output is correct.
    – Steven W. Klassen
    Nov 20 at 5:13










  • If the expected output is to condense/drop leading and trailing whitespace and extra whitepace between words, you'll best solve this with two flags: 1) one flag records that you've seen a space so that when you encounter a letter you first output a space, except when you are translating your special newline code or when: 2) another flag records that you've seen the first non-space character on the current line -- if that is not set, you never output any leading space.
    – paddy
    Nov 20 at 5:18












  • my teacher has a program that runs my version against hers with the same text file. In her version, it doesn't have that extra space, even though there is a space after the :! in the text file! hmm.... would it be possible for me to read in all characters ignoring white space, and then add them in correctly afterward in the display function? My teacher's program seems to be ignoring all white spaces except the ones that exist between words. God, I wish I could just use strings.
    – Liam Ihasz
    Nov 20 at 5:20










  • @paddy If I am only reading one char at a time, how can I know if the space I am reading is the first one in the line?
    – Liam Ihasz
    Nov 20 at 5:28














  • 2




    You should use constexpr instead of #define. It is less error-prone.
    – Fei Xiang
    Nov 20 at 5:12






  • 2




    It looks to me like the space you are complaining about should be there. It is in your input file (a space after the :!) hence unless your requirements were also to strip leading whitespace, I think your current output is correct.
    – Steven W. Klassen
    Nov 20 at 5:13










  • If the expected output is to condense/drop leading and trailing whitespace and extra whitepace between words, you'll best solve this with two flags: 1) one flag records that you've seen a space so that when you encounter a letter you first output a space, except when you are translating your special newline code or when: 2) another flag records that you've seen the first non-space character on the current line -- if that is not set, you never output any leading space.
    – paddy
    Nov 20 at 5:18












  • my teacher has a program that runs my version against hers with the same text file. In her version, it doesn't have that extra space, even though there is a space after the :! in the text file! hmm.... would it be possible for me to read in all characters ignoring white space, and then add them in correctly afterward in the display function? My teacher's program seems to be ignoring all white spaces except the ones that exist between words. God, I wish I could just use strings.
    – Liam Ihasz
    Nov 20 at 5:20










  • @paddy If I am only reading one char at a time, how can I know if the space I am reading is the first one in the line?
    – Liam Ihasz
    Nov 20 at 5:28








2




2




You should use constexpr instead of #define. It is less error-prone.
– Fei Xiang
Nov 20 at 5:12




You should use constexpr instead of #define. It is less error-prone.
– Fei Xiang
Nov 20 at 5:12




2




2




It looks to me like the space you are complaining about should be there. It is in your input file (a space after the :!) hence unless your requirements were also to strip leading whitespace, I think your current output is correct.
– Steven W. Klassen
Nov 20 at 5:13




It looks to me like the space you are complaining about should be there. It is in your input file (a space after the :!) hence unless your requirements were also to strip leading whitespace, I think your current output is correct.
– Steven W. Klassen
Nov 20 at 5:13












If the expected output is to condense/drop leading and trailing whitespace and extra whitepace between words, you'll best solve this with two flags: 1) one flag records that you've seen a space so that when you encounter a letter you first output a space, except when you are translating your special newline code or when: 2) another flag records that you've seen the first non-space character on the current line -- if that is not set, you never output any leading space.
– paddy
Nov 20 at 5:18






If the expected output is to condense/drop leading and trailing whitespace and extra whitepace between words, you'll best solve this with two flags: 1) one flag records that you've seen a space so that when you encounter a letter you first output a space, except when you are translating your special newline code or when: 2) another flag records that you've seen the first non-space character on the current line -- if that is not set, you never output any leading space.
– paddy
Nov 20 at 5:18














my teacher has a program that runs my version against hers with the same text file. In her version, it doesn't have that extra space, even though there is a space after the :! in the text file! hmm.... would it be possible for me to read in all characters ignoring white space, and then add them in correctly afterward in the display function? My teacher's program seems to be ignoring all white spaces except the ones that exist between words. God, I wish I could just use strings.
– Liam Ihasz
Nov 20 at 5:20




my teacher has a program that runs my version against hers with the same text file. In her version, it doesn't have that extra space, even though there is a space after the :! in the text file! hmm.... would it be possible for me to read in all characters ignoring white space, and then add them in correctly afterward in the display function? My teacher's program seems to be ignoring all white spaces except the ones that exist between words. God, I wish I could just use strings.
– Liam Ihasz
Nov 20 at 5:20












@paddy If I am only reading one char at a time, how can I know if the space I am reading is the first one in the line?
– Liam Ihasz
Nov 20 at 5:28




@paddy If I am only reading one char at a time, how can I know if the space I am reading is the first one in the line?
– Liam Ihasz
Nov 20 at 5:28












1 Answer
1






active

oldest

votes


















1














Type, type, type away :!
compile.
Run.
Hip hip hooray! :! No errors. today! :!


ok. the first thing you do in formatting is remove all the newlines 'n' in the character array and that leaves you with



Type, type, type away :!compile.Run.Hip hip hooray! :! No errors today! :!


then you replace all the !'s preceded by :'s with 'n' but if you notice that in this state all your :!'s have a non whitespace character in the next index position save one.



 :! No errors


and that's your error, because it then replaces your sequence as n No errors



changing your input data to



Type, type, type away :!
compile.
Run.
Hip hip hooray! :!No errors today! :!


fixes that extra space problem.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53386560%2fc-reading-characters-in-from-a-file-char-by-char-using-only-char-arrays%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Type, type, type away :!
    compile.
    Run.
    Hip hip hooray! :! No errors. today! :!


    ok. the first thing you do in formatting is remove all the newlines 'n' in the character array and that leaves you with



    Type, type, type away :!compile.Run.Hip hip hooray! :! No errors today! :!


    then you replace all the !'s preceded by :'s with 'n' but if you notice that in this state all your :!'s have a non whitespace character in the next index position save one.



     :! No errors


    and that's your error, because it then replaces your sequence as n No errors



    changing your input data to



    Type, type, type away :!
    compile.
    Run.
    Hip hip hooray! :!No errors today! :!


    fixes that extra space problem.






    share|improve this answer


























      1














      Type, type, type away :!
      compile.
      Run.
      Hip hip hooray! :! No errors. today! :!


      ok. the first thing you do in formatting is remove all the newlines 'n' in the character array and that leaves you with



      Type, type, type away :!compile.Run.Hip hip hooray! :! No errors today! :!


      then you replace all the !'s preceded by :'s with 'n' but if you notice that in this state all your :!'s have a non whitespace character in the next index position save one.



       :! No errors


      and that's your error, because it then replaces your sequence as n No errors



      changing your input data to



      Type, type, type away :!
      compile.
      Run.
      Hip hip hooray! :!No errors today! :!


      fixes that extra space problem.






      share|improve this answer
























        1












        1








        1






        Type, type, type away :!
        compile.
        Run.
        Hip hip hooray! :! No errors. today! :!


        ok. the first thing you do in formatting is remove all the newlines 'n' in the character array and that leaves you with



        Type, type, type away :!compile.Run.Hip hip hooray! :! No errors today! :!


        then you replace all the !'s preceded by :'s with 'n' but if you notice that in this state all your :!'s have a non whitespace character in the next index position save one.



         :! No errors


        and that's your error, because it then replaces your sequence as n No errors



        changing your input data to



        Type, type, type away :!
        compile.
        Run.
        Hip hip hooray! :!No errors today! :!


        fixes that extra space problem.






        share|improve this answer












        Type, type, type away :!
        compile.
        Run.
        Hip hip hooray! :! No errors. today! :!


        ok. the first thing you do in formatting is remove all the newlines 'n' in the character array and that leaves you with



        Type, type, type away :!compile.Run.Hip hip hooray! :! No errors today! :!


        then you replace all the !'s preceded by :'s with 'n' but if you notice that in this state all your :!'s have a non whitespace character in the next index position save one.



         :! No errors


        and that's your error, because it then replaces your sequence as n No errors



        changing your input data to



        Type, type, type away :!
        compile.
        Run.
        Hip hip hooray! :!No errors today! :!


        fixes that extra space problem.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 at 6:28









        johnathan

        2,158819




        2,158819






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53386560%2fc-reading-characters-in-from-a-file-char-by-char-using-only-char-arrays%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            Origin of the phrase “under your belt”?