2014-04-03 83 views
0

我目前有這樣的代碼,但我希望能夠輸出到.csv文件,而不是僅僅打印到屏幕上。有誰知道如何做到這一點?如何將一個字符串寫入.csv文件?

#include <iostream> 
#include <fstream> 
#include <algorithm> 

using namespace std; 

string Weather_test; 

int main() 
{ 
    ifstream Weather_test_input; 
    Weather_test_input.open("/Users/MyName/Desktop/Weather_test.csv"); 

    getline(Weather_test_input, Weather_test, '?'); 

    Weather_test.erase(remove_if(Weather_test.begin(), Weather_test.end(), ::isalpha), Weather_test.end()); 

    cout << Weather_test; 

    return 0; 
} 
+0

你需要做一個文件處理程序 - 也嘗試搜索我相信你可以在這裏找到答案 – Jeef

+0

只需谷歌的C + +寫入文件。 – RedX

回答

0

感謝你在這裏的人都是真正的驚人!

我設法讓我的最後一段代碼(從我的.csv文件中刪除所有字母)。這是後代

#include <iostream> 
#include <fstream> 
#include <algorithm> 

using namespace std; 

string Weather_test; 

int main() 
{ 
    ifstream Weather_test_input; 
    Weather_test_input.open("/Users/MyName/Desktop/Weather_test.csv"); 

    getline(Weather_test_input, Weather_test, '?'); 

    Weather_test.erase(remove_if(Weather_test.begin(), Weather_test.end(), ::isalpha), Weather_test.end()); 

    ofstream Weather_test_output("/Users/MyName/Desktop/Weather_test_output.csv", ios::app); 
    Weather_test_output << Weather_test << std::endl; 
    Weather_test_output.close(); 

    cout << Weather_test; 

    return 0; 
} 

再次感謝所有!

0

寫入字符串到CSV文件就像寫一個字符串的任何文件:

std::string text = "description" 
output_file << description << ", " << 5 << "\n"; 

在你的榜樣,你不能寫一個ifstream。你可以寫信給ofstreamfstream,但不是ifstream

因此,無論是打開文件進行閱讀和寫作,或閱讀後關閉並打開寫作。

0

要寫入csv是創建一個ostream並打開文件名爲"*.csv"。您可以以同樣的方式在此對象上使用operator<<如您使用它以前寫的標準輸出,標準::法院:

std::ofstream f; 
f.open("file.csv", std::ios::out); 
if (!f) return -1; 
f << Weather_test; 
f.close(); 
2

如果Weather_test字符串格式正確。

ofstream Weather_test_output("path_goes_here.csv", ios::app); 
     // this does the open for you, appending data to an existing file 
Weather_test_output << Weather_test << std::endl; 
Weather_test_output.close(); 

如果它沒有正確格式化,那麼你需要將它分隔成「字段」並在它們之間用逗號來書寫它們。這是一個單獨的問題。

相關問題