Writing .csv files from C++

前端 未结 6 774
走了就别回头了
走了就别回头了 2020-12-23 11:18

I\'m trying to output some data to a .csv file and it is outputting it to the file but it isn\'t separating the data into different columns and seems to be outputting the da

6条回答
  •  清歌不尽
    2020-12-23 11:48

    There is nothing special about a CSV file. You can create them using a text editor by simply following the basic rules. The RFC 4180 (tools.ietf.org/html/rfc4180) accepted separator is the comma ',' not the semi-colon ';'. Programs like MS Excel expect a comma as a separator.

    There are some programs that treat the comma as a decimal and the semi-colon as a separator, but these are technically outside of the "accepted" standard for CSV formatted files.

    So, when creating a CSV you create your filestream and add your lines like so:

    #include 
    #include 
    int main( int argc, char* argv[] )
    {
          std::ofstream myfile;
          myfile.open ("example.csv");
          myfile << "This is the first cell in the first column.\n";
          myfile << "a,b,c,\n";
          myfile << "c,s,v,\n";
          myfile << "1,2,3.456\n";
          myfile << "semi;colon";
          myfile.close();
          return 0;
    }
    

    This will result in a CSV file that looks like this when opened in MS Excel:

    Image of CSV file created with C++

提交回复
热议问题