2011-02-28 49 views
0

我有一個包含此行一個文本文件:如何修改文本在一個文本文件

C:\Program Files\app\ 

我想讀它成爲這樣的:

C:\\Program Files\\app\\ 

我知道如何讀文件在visual C++中,但是如何在每次創建斜線時添加一個斜線()。

char str[200]; 
    fstream file_op("C:\\path.txt",ios::in); 
    file_op >> str; 
    file_op.close(); 

回答

1

要做到這一點,最簡單的方法是通過循環:

char newPath[MAX_PATH]; 
int newCount = 0; 
for(int i=0; i < strlen(str); i++) 
{ 

    if(str[i] == '\') 
    { 
     newPath[newCount++] = str[i]; 
    } 
    newPath[newCount++] = str[i]; 
} 

請注意,您不能更改文件。您將不得不將新字符串寫入新文件。我沒有使用boost或任何其他庫,因爲這些不是默認的VisualC++的一部分,你的標籤說你需要這個用於VisualC++

-1

在VB中,你可以使用String.Split()與他人代替某些字符,你可能會想嘗試這樣或谷歌使用「正則表達式」的(不知道propper皆可使用,但現在我知道它旨在取代和編輯字符串)

+0

我們正在談論C++ ... – CharlesB 2011-02-28 11:04:00

+0

是的,在VS你有一切都很好。在每種語言中都有.NET特性......比如字符串函數,正則表達式等......即使它沒有直接實現,你也可以在googleing「regex C++」中找到它,第一個鏈接是「http: //www.drdobbs.com/cpp/184404797「......對不起,如果這聽起來像曳,但我在這裏完全白癡包圍!?在另一個問題上與一些混蛋進行了類似的討論...... – Husky110 2011-02-28 14:58:43

2

使用boost:

#include <boost/algorithm/string/replace.hpp> 
#include <fstream> 
using namespace std; 
int main(int argc, char const* argv[]) { 
    string line; 
    ifstream file_op("D:\\path.txt"); 
    ofstream file_out("D:\\out.txt"); 
    while(getline(file_op, line)) { 
    boost::replace_all(line, "\\", "\\\\"); 
    file_out << line << '\n'; 
    } 
    // file_op and file_out are closed on exit 
    return 0; 
}