Jump to content

[C++] write everything that exists in list into a file.

WillLTT
Go to solution Solved by KNG_HOLDY,

@WillLTT 

1) so if im not wrong you didnt start writting the reading the file part yet right?

if i where you i would start with that

 

https://thispointer.com/c-how-to-read-a-file-line-by-line-into-a-vector/

 

2) if you want to understand the code and not just copy & paste i would implement the saving part as followed

open a outputstream like ofstream

itterate through your vector you want to save and write each item in the stream

afterwards close the stream

 

something like this

 ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();

 

links: https://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream

http://www.cplusplus.com/doc/tutorial/files/

 

 

lets say i have 5 string in my vector list, i want to take all those into a file as explained below:

the reason im trying to do this is i want to save the list for future use.

 

the list code im using is:

std::vector<std::string> learned_{"Hello", "This", "Is", "A", "List"};

 

but i dont want to do like list[0] etc. i want to automatically count them all and convert them to normal string's and write them somewhat like this:

Hello
This
Is
A
List

into a file. i think this could be done by using

for

 

and then after when the app has restarted and forgotten everything, i want to load these strings back into the list. with:

learned_.push_back(file);

 

The problem with this as i will not know how many things there are in the list.

so this is quite the problem.

Link to comment
Share on other sites

Link to post
Share on other sites

18 minutes ago, WillLTT said:

The problem with this as i will not know how many things there are in the list.

Vectors aren't like arrays. You can push in as many items as you like without declaring the size in advance.

 

For the sake of argument, if you were using a fixed size array then you could have the first line in the file be the size of the array, then create an array with that size when you load the file back.

 

For writing to the file, here's an elegant solution https://stackoverflow.com/questions/6406356/how-to-write-vector-values-to-a-file#6406411

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to comment
Share on other sites

Link to post
Share on other sites

just to be clear - you want a vector of strings to be written into a file, each item seperated by a line break

and when you start your programm you want to read that same file and fill your vector again with all these items?

 

saving:

(1) just open a filewriter and itterate through every item and append it to that filewriter aka the file

 

loading:

1)read the file line by line and each line is a new item => 

learned_.push_back(item); 

istead of push_back(file)

 

 

 

your problem sounds quite easy to realize so im not sure if i understood it fully

 

Link to comment
Share on other sites

Link to post
Share on other sites

35 minutes ago, KNG_HOLDY said:

just to be clear - you want a vector of strings to be written into a file, each item seperated by a line break

and when you start your programm you want to read that same file and fill your vector again with all these items?

Correct! i started using c++ a few weeks ago, so sorry for calling vectors for lists and things like that

 

Quote

1)read the file line by line and each line is a new item => 

Easier said than done, ive googled for a while "read a file line by line c++" i did that before starting this thread also. but i cant find much results.

 

i found this:

but it reads it everyline sideways.. so like line[0] is '[' and secound line is 'a' when line 0 really is [memory]

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, KNG_HOLDY said:

@WillLTT maybe post your code? 

yes, do you want everything or int main or ?

1 minute ago, KNG_HOLDY said:

do you just want the result or do you want to learn it?

both, i want to try understand it before i use it.

Link to comment
Share on other sites

Link to post
Share on other sites

4 minutes ago, KNG_HOLDY said:

@WillLTT i just want everything i need to reproduce your issue - i dont know where your stuff is so i cant tell - if you are not sure just post everything 

https://pastebin.com/UQTdHNwt

thats the full code.

 

there is alot of unfinished parts that i have not added yet.

Link to comment
Share on other sites

Link to post
Share on other sites

@WillLTT 

1) so if im not wrong you didnt start writting the reading the file part yet right?

if i where you i would start with that

 

https://thispointer.com/c-how-to-read-a-file-line-by-line-into-a-vector/

 

2) if you want to understand the code and not just copy & paste i would implement the saving part as followed

open a outputstream like ofstream

itterate through your vector you want to save and write each item in the stream

afterwards close the stream

 

something like this

 ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();

 

links: https://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream

http://www.cplusplus.com/doc/tutorial/files/

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

13 minutes ago, KNG_HOLDY said:

open a outputstream like ofstream

itterate through your vector you want to save and write each item in the stream

afterwards close the stream

makes sense!

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, KNG_HOLDY said:

yeah why?

i was just wondering 🙂

Link to comment
Share on other sites

Link to post
Share on other sites

2 hours ago, WillLTT said:

<snip>

Something like this ? (enable C++14)

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
#include <optional>

bool
SaveStringVectorToFile(const std::vector<std::string>& v, const std::string& fileName)
{
    auto oFile = std::ofstream(fileName);
    if (!oFile.is_open())
    {
        return false;
    }

    std::copy(v.begin(), v.end(),
              std::ostream_iterator<std::string>(oFile, "\n"));
    return oFile ? true : false;
}

std::optional<std::vector<std::string>>
LoadStringVectorFromFile(const std::string& fileName)
{
    auto iFile = std::ifstream(fileName);
    if (!iFile.is_open())
    {
        return std::nullopt;
    }

    const auto v = std::vector<std::string>(std::istream_iterator<std::string>(iFile),
                                            std::istream_iterator<std::string>());
    return iFile.bad() ? std::nullopt : std::make_optional(v);
}

int
main()
{
    //Save existing vector to file...
    const auto learned_ = std::vector<std::string>{"Hello", "This", "Is", "A", "List"};
    if (!SaveStringVectorToFile(learned_, "Test.txt"))
    {
        std::cout << "Failed to save to file!\n";
        return 1;
    }

    //Load new vector from file...
    const auto fromFile = LoadStringVectorFromFile("Test.txt");
    if (!fromFile)
    {
        std::cout << "Failed to load from file!\n";
        return 2;
    }

    //Print loaded contents...
    std::cout << "Loaded from file: \n";
    for (const auto& str : *fromFile)
    {
        std::cout << str << '\n';
    }

    return 0;
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, Unimportant said:

--snip--

i got the question answeared before you posted this but thank you anyway! :D

Link to comment
Share on other sites

Link to post
Share on other sites

4 minutes ago, WillLTT said:

i got the question answeared before you posted this but thank you anyway! :D

You might want to add error handling tough, a quick glimpse at the other code shows it does not check if opening files succeeded before reading/writing , etc...

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Unimportant said:

You might want to add error handling tough, a quick glimpse at the other code shows it does not check if opening files succeeded before reading/writing , etc...

yeah im going to add try catch blocks, i just wanted to test everything first 🙂

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×