Home > other >  How to make my ifstream "input" look the same in program like it does in file
How to make my ifstream "input" look the same in program like it does in file

Time:07-02

I am new to programming, and currently I am learning C . I am making this kind of project that I learn on, in which there already exists some "premade items", and items that you can create yourself and then be shown. For this, I am currently learning and using fstream.

The text in my file looks like this:

Text in file

But this is how that same text looks in my output:

Text in code

How can I make it so that the text which I get in the output looks the same as the text in my file?

Here is the part of code responsible for this action:

void existingitems(){

    ifstream existingitems("existingitems.txt",ios::in);
    vector<string>exitems;
    string inputs;
    while(existingitems >> inputs){
        exitems.push_back(inputs);
    }
    for(string exisitems : exitems){
        cout<<exisitems;
    }       
}

CodePudding user response:

The lines of text in the file are delimited by line breaks. operator>> skips leading whitespace before reading data (unless std::noskipws is used), and then stops reading when it encounters whitespace. Spaces, tabs, and line breaks are all considered whitespace by operator>>.

So, in your case, you end up reading individual words into your vector (ie Primordial, Mark, -Health, 300, etc), not whole lines as you are expecting.

When you are then displaying the strings in the vector, you are not outputting any delimiters between each string, whether that be spaces or line breaks or whatever. So everything gets mashed together in one long string.

If you want the output to look exactly like the file, use std::getline() instead of operator>>, and be sure to output a line break after each string:

void existingitems(){

    ifstream inputFile("existingitems.txt");
    vector<string> existingitems;
    string input;
    while (getline(inputFile, input)){
        existingitems.push_back(input);
    }
    for(string item : existingitems){
        cout << item << '\n';
    }       
}
  •  Tags:  
  • c
  • Related