2014-01-21 70 views
-1

我是使用C++進行編程的新手。我想寫一些數據到一個CSV文件。 這是我的代碼,試圖做到這一點,但它只寫1列( 而不是另一(年)列1變量(人口)。將數據從C++寫入csv

#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; 
} 

有人可以告訴我爲什麼它只是寫入文件的人口值而不是年份? 謝謝!

+0

',year;'<===你打算怎麼做? –

+0

試試'<<'操作符:'USPopulation << population [index] << year;'。因爲你想要一個CSV文件'USPopulation << population [index] <<「,」<< year << std :: endl' –

回答

5

您正在使用comma operator這裏:

USPopulation << population[index], year; 
//        ^

的效果評估

USPopulation << population[index] 

和丟棄的結果,然後計算並返回

year 

所以,你需要像

USPopulation << population[index] << "," << year; 

假設您希望分隔符爲單個,

3

它應該是:

USPopulation << population[index] << "," << year; 

編輯:通過使用機會是comma operator(這是更好它不是一個運營商這裏讓你意識到這一點:)):

在C和C++編程語言中,逗號運算符(由令牌表示)是一個二元運算符,用於評估其第一個操作數並放棄結果,然後評估第二個操作數並返回此值(和類型)。

0

爲什麼你不使用它像這樣的代碼?

USPopulation << population[index] << ", " << year; 
+0

B'coz OP不知道這個 – P0W

+0

你想用哪種格式讓你文件?請分享 –