2016-07-23 98 views
0

如果我的文本文件看起來如此..如何使用C++在特定位置將數據從矢量寫入文本文件?

[email protected] 3223434324數據1數據2

[email protected] 2343454454數據3數據4

我一直在使用矢量讀取這些值。 我需要在文件第一行的末尾添加一個字符串。 我該怎麼辦? 我的代碼如下:

system("cls"); 
cout << "\nView proposal\n"; 
fstream file1; 
string ap, aname, aphno; 
file1.open("C:\\Users\\Nandhu\\Desktop\\glosys\\joinpolicy.txt", 
    ios::in|ios::app); 
while(!file1.eof()) 
{ 
    while(getline(file1, text)) 
    { 
     istringstream xstream(text); 
     vector<string> vcol; 
     while(getline(xstream, word, ',')) 
     { 
      vcol.push_back(word); 
     } 
     vec.push_back(vcol); 
    } 
    file1.close(); 
} 
for(vector<vector<string> >::iterator itr = vec.begin(); 
    itr != vec.end(); itr++) 
{ 
    for(vector<string>::iterator itr2 = itr->begin(); 
     itr2 != itr->end(); itr2++) 
    { 
     string str; 
     str = *itr2; 
     cout << str << " "; 
    } 
    cout << "\n"; 
} 
cout << "\n1.Approve"; 
cout << "\n2.Reject"; 
cout << "\nDo you wish to approve?"; 
cin >> ans;  
if(ans == 'y') 
{ 
    file1.open("C:\\Users\\Nandhu\\Desktop\\glosys\\joinpolicy.txt", 
     ios::in|ios::app); 
    file1.seekg(0); 
    cout << "\nEnter the customer id you wish to approve for:"; 
    cin >> aname; 
    vec.clear(); 
    if(file1.is_open()) 
    { 
     while(getline(file1, text)) 
     { 
      istringstream xstream(text); 
      vector<string> vcol; 
      while(getline(xstream, word, ',')) 
      { 
       vcol.push_back(word); 
      } 
      vec.push_back(vcol); 
     } 
     file1.close(); 
    } 

    for(vector<vector<string> >::iterator itr = vec.begin(); 
     itr != vec.end(); itr++) 
    { 
     vector<vector<string> > vec; 
     vector<string> vcol; 

     for(vector<string>::iterator itr2 = itr->begin(); 
      itr2 != itr->end(); itr2++) 
     { 
      string str; 
      str=*itr2; 
      if(str==aname) 
      { 
       itr + 3;  
       file1.open("C:\\Users\\Nandhu\\Desktop\\glosys\\joinpolicy.txt", 
        ios::out|ios::app); 
       vector<string>.insert(itr->end(), "approved"); 
       file1 << "approved"; 
       cout << "approved"; 
       file1.close(); 
      } 
     } 
    } 
}  
break; 
+1

似乎缺少一些代碼和格式是遍佈店鋪請更正 –

+0

請修復格式和縮進代碼 –

+0

我的代碼現在好嗎? – nandhu

回答

0

您不能直接在文件中插入數據。您只能重寫整個文件或在最後附加到該文件。

插入數據在中間,你有幾個選擇:

1)讀取文件到內存緩衝區,轉換它根據需要,然後將該文件截斷爲零長度,並從緩衝區改寫。

2)作爲1,不是截斷原始文件,而是寫一個新的(臨時)文件,然後在原始文件上重命名它。

3)確定需要進行更改的點,在點之後讀取所有內容緩衝區並進行更改,然後將文件截斷爲之前標識的大小,然後將內存緩衝區寫入文件中模式。

4)內存映射文件,進行所需的更改並將其刷新到文件。

+0

這是一個小例子代碼,這是最受歡迎的.. – nandhu

+0

我現在真的沒有時間了,但至少現在你知道要研究什麼。 –

相關問題