2013-10-28 46 views
0

我正在嘗試編寫一些代碼來替換向量中的某個數字。因此,如果矢量包含12345之類的東西,並且某人決定用0替換或更改元素[4],則它將寫入文件12340.如何替換矢量中的特定元素?

到目前爲止,通過下面的代碼,我最終只更換了文件中的第一個數字。並使用

theFile << newIn.at(count) << endl; 

而不是

theFile << *i << endl; 

似乎不工作。

如何修改特定的矢量元素,然後將整個矢量寫入文件?

//change/replace/delete 
cout << "What would you like to replace it with?" << endl; 
cin >> newIn; 
fileInfo.at(count) = newIn; 

//open 
fstream theFile("numbers.txt"); 

//write changes 
ofstream thefile; 
for(vector<char>::const_iterator i = fileInfo.begin(); i != fileInfo.end(); i++) 
{ 
    theFile << *i << endl; 
} 
+1

什麼是「計數」?它在哪裏以及如何獲得它的價值? –

+0

錯誤是什麼?你是否試圖將其打印到屏幕上?當你替換'fileInfo.at(count)= newIn;'時,結果是什麼? fileInfo如何聲明? – user1810087

+0

@IgorTandetnik - count只是一個侵權號碼...程序一次讀取一個文件的內容,並詢問您是否要替換該項目。每次用戶選擇不更改項目時,計數都會增加。我想通過這種方式我可以跟蹤我在矢量中的位置。 – UndefinedReference

回答

0

嘗試使用fileInfo [count] = newIn;

如果這不起作用,作爲一個完整性檢查,您應該仔細檢查您是否正確讀取了矢量,並且還使用cout打印矢量狀態以及寫入你的輸出流。

0

從STL使用複製算法:

#include <iostream> 
#include <fstream> 
#include <vector> 
#include <algorithm> 
#include <iterator> 

using namespace std; 
string fileName("resources\\data.txt"); 
ofstream outputFile(fileName); 

vector<int> v = { 0, 1, 2, 3, 4 }; 
v[3] = 9; 

copy(v.begin(), v.end(), ostream_iterator<int>(outputFile, ",")); 

在副本的最後一個參數都有我選擇是逗號分隔。你當然可以傳遞一個空字符串到你要求的東西。