You are on page 1of 1

How to write in .

CSV file from C



#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
typedef std::string String;
using namespace std;
int main(){


std::fstream file;
char* filename = "c:\\Coupling\\2.csv" ;
//file.open( filename);
file.open(filename, ios_base::in | ios_base::out | ios_base::trunc);
if(!file.is_open()){
std::cout << "File not found!\n";
return 1;
}

int numOfCols=1;
for(int i = 0; i < 5; i++)
{
file << i;
if((numOfCols<5))
{file << ",";//print comma (,)
}
if((i+1)%5==0)
{
file << "\n";//print newline after 5th value
numOfCols=1;//start from column 1 again, for the next
line
}
numOfCols++;
}
file << "\n";// last new line

}

You might also like