csv file

Hi. I need to send data to an output file that can be opened in excel, so I made my output file a csv file. However, I need to include commas and quotation marks in some of the cells. How do I make it so that the comma is interpreted as part of the data, and not a delimiter? How do I include a quotation mark in a cout command? For instance, how would I make it so that the following is included in a single cell of the file, when it is opened in excel:

a,"b"

I've tried searching on google. I thought it'd be easy to find a solution but I've had no luck. Some websites talk about escape sequences, which don't seem to be working for me, and others talk about parsing, which is completely unfamiliar to me. Are there any quick and easy solutions? Thanks.
First, isolate the two separate problems. For example, edit a text file and put something like this in it:
asdf,asdf,"asdf asdf","1, 2, 3",asdf


Does Excel load it as expected?

As for how to output double quotes, one way is to escape them with a backslash. For example:
cout << "The word \"abc\" is output in quotes." << endl;
Yes, excel loads it as follows (each | represents a cell border) when I save the text as a csv file:

asdf | asdf | asdf asdf | 1, 2, 3 | asdf

I concluded that to get a comma or a quotation mark to be part of the cell data, I'd need to enclose them in quotation marks using the escape sequence \". So then I tried this simple program:

1
2
3
4
5
6
7
8
9
10
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    ofstream outfile;
    outfile.open("results.csv");
    outfile<<"\",\",\"\",\"\",a";
    return 0;
}


I predicted that the file when opened in excel would look like this:

, | "," | a

However, it actually looks like this, as if "," is a delimiter:

, | | | a

Also, if I replace line 8 with outfile<<"\",\",\"\"-\"\",a"; I expected this:

, | "-" | a

But I get this instead:

, | #VALUE! | a

the cell that says #VALUE! has the formula =-""

If I replace line 8 with outfile<<"\",\",\"\"\"\",a"; I expect this:

, | "" | a

But I get this:

, | " | a

EDIT: Nevermind, I figured it out. Thanks.
Last edited on
Topic archived. No new replies allowed.