2014-04-03 50 views
0

我目前有一個.csv文件,該文件應該只包含數值,但某些列中存在錯誤,表示包含文本。我想知道去除這些字符的最佳方式是什麼。從只包含數字的.csv文件中刪除字符

我正在查看使用str.erase(std::remove(str.begin(), str.end(), 'xxxxxxx'), str.end());。爲此,我需要將我的數據讀入字符串,然後從該字符串中刪除字母表。我現在正在這樣做(我使用「?」作爲分隔符,因爲我知道我的文件中沒有)。

#include <iostream> 
#include <fstream> 
#include <algorithm> 
using namespace std; 

string Weather_test; 
char chars[] = {'A','a','B','b','C','c','D','d','E','e','F','f','G','g','H','h','I','i','J','j','K','k','L','l','M','m','N','n','O','o','P','p','Q','q','R','r','S','s','T','t','U','u','V','v','W','w','X','x','Y','y','Z','z'}; 

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

    getline(Weather_test_input, Weather_test, '?'); 

    str.erase(remove(Weather_test.begin(), Weather_test.end(), chars[!eof]), Weather_test.end(); 

    cout << Weather_test; 

    return 0; 
} 

這個問題是我不知道如何處理字符[!eof]部分。有什麼建議麼?

在此先感謝!

+0

什麼是'eof'?它並未在我的環境中定義。順便說一句,你的程序不會編譯,因爲'str'沒有被定義。你的意思是'Weather_test.erase'而不是'str.erase' –

+0

我的意思是'Weather_test.erase'而不是'str.erase' – Taylrl

回答

2

我建議你使用std::remove_if,而不是std::isalpha。也許類似

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

好的。這似乎很有道理。我剛剛正在研究使用remove_if。你知道我需要包含哪個庫來讓remove_if工作嗎?目前,我收到一個錯誤,指出「沒有匹配函數調用'remove_if'」。 – Taylrl

+0

@ user1432792它位於標準的''標題中。並且你正在包含'std :: isalpha'的正確頭文件(按照參考鏈接查看哪一個)?你能否提供*完整*錯誤?它可能包含其他提示。 –

+0

我在頂部添加了,錯誤只是說'沒有匹配的函數調用'remove_if'「。就是這樣,我也會看看參考鏈接。 – Taylrl

0

我設法做到了。這是最終的解決方案!

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

非常感謝Joachim Pileborg!

相關問題