简体   繁体   中英

C++, putting vector data into a .csv file

I'm working on something simple, and i want it to be able to take everything within a vector and put it into a .CSV file, where every row would be a new vector and the columns being each position within the vector.

This is my current code, however whenever I open the CSV file it is completely empty.

Any help would be greatly appreciated!

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    ofstream myfile;
    myfile.open("test.csv");

    vector<int> arrayOne = { 10, 20, 30, 40, 50 };


    for (int i = 0; i < arrayOne.size(); i++)
    {
        myfile << arrayOne.at(i) << ",";
    }

    cin.ignore();
    cin.ignore();
    return 0;
}

As the marked answer is totally correct in the function it demands from OP, but is derivatives in the code drastically. Which can result in an undebugable code or alter the behavior OP intended. pls consider this code:

#include <iostream>
#include <fstream>
#include <vector>

// removed "using namespace std"

int main()
{
    std::ofstream myfile; // added "std::"
    myfile.open("test.csv");

    std::vector<int> arrayOne { 10, 20, 30, 40, 50 };

    for (int i = 0; i < arrayOne.size(); i++) { // added "{"
        myfile << arrayOne.at(i) << ",";
    } // added "{"

    myfile.close(); // <- note this correction!!
    std::cin.ignore(); // added this
    std::cin.ignore(); // added this
    return 0;
}
  • consider not using using namespace std . This namespace includes hundreds of thousand of functions. you may collide with one of them and this is a pain to debug.
  • The marked answer removes the parentheses {} at the for-loop . NEVER do that, you may run into undebugable problems, when you add one line to your for-loop . This line is no executed in the loop.
  • The answer also remove vital code from the OP twice: std::cin.ignore();

Close your file like this:

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    ofstream myfile;
    myfile.open("test.csv");

    vector<int> arrayOne = { 10, 20, 30, 40, 50 };

    for (int i = 0; i < arrayOne.size(); i++)
        myfile << arrayOne.at(i) << ",";

    myfile.close();
    return 0;
}

The point here is, output streams are often buffered. When you close the file, close() function ensures, any pending output sequence is written to the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM