Hey everybody,

I need to send the output data from a .cpp file to a .csv file so that I can import it into excel for further work. I was reading some stuff online, but I was getting confused.

I need the data in the .csv file to look like:

"a1" , "a2" , "a3" , ... , "aN"
"b1" , "a2" , "b3" , ... , "bN"
...

Two lines should be good for now, since they will each become either a row or column in excel.

So if anybody can help me write generated data from a .cpp file to a .csv file, I would greatly appreciate it.

Do you know how to open a file and write to it? You can put the " character in the file by using the escape sequence \".

#include <fstream>
using std::ofstream;

int main()
{
   char *string1[] = {"a1","a2","a3","a4"};
   char *string2[] = {"b1","b2","b3","b4"};

   ofstream out("filename.csv");
   for(int i = 0; i < 4; i++)
   {
      cout << "\"" << string1[i] << "\"";
      if( < 3)
        cout <<", ";
   }
   cout << "\n";
   for(int i = 0; i < 4; i++)
   {
      cout << "\"" << string2[i] << "\"";
      if( < 3)
        cout <<", ";
   }
}

You can shorten the code a bit by putting the loop in a function of its own and passing to it the string to be sent to the file.

Thanks a lot. I'm pretty new to C++ and this is for a project at work. Did you run that code and get zero errors? I copied your code and tried to compile it, but the cout commands are giving me a a problem.

line 12 (and 19): cout was not declared in this scope
line 13 (and 20): expected primary-expression before '<" token

I think an "i" fixes lines 13 and 20.

Also, that data I'm generating will be numbers... so some changes will need to be made. Instead of a string, I'd have to use a vector or array... which is pretty similar to the string.

I didn't compile the code I posted -- should have included <iostream> and using std::cout statememt.

The code I posted is just one example of how to write the csv file. Using a vector you would want write it in a loop, remembering that numeric data is not enclosed in quotes.

I got it now, thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.