我是c ++编程的新手.我想将一些数据写入csv文件.这是我的代码尝试这样做,但它只在列中写入1个变量(填充)而不是另一个(年).
#include <fstream>
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
/ data generation/
ofstream USPopulation;
USPopulation.open("D:\\2.csv");
USPopulation << "Population,Year" << endl;
int year = 1790;
for (int index = 0; index < count; index++)
{
USPopulation << population[index], year; / this only writes the population values /
USPopulation << endl;
year += 1;
}
USPopulation.close();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我为什么它只是写人口价值而不是文件的年数?谢谢!
您在这里使用逗号运算符:
USPopulation << population[index], year;
// ^
Run Code Online (Sandbox Code Playgroud)
效果是评估
USPopulation << population[index]
Run Code Online (Sandbox Code Playgroud)
并丢弃结果,然后评估并返回
year
Run Code Online (Sandbox Code Playgroud)
所以,你需要类似的东西
USPopulation << population[index] << "," << year;
Run Code Online (Sandbox Code Playgroud)
假设您希望分隔符为单个分隔符,.