2016-10-18 38 views
0

相對較新的C++,下面是我的代碼:通過數組循環存儲重複字符串,並添加了相同的字符串C++的值

void displaydailyreport() 
{ 
    std::string myline; 

    string date[100]; // array for dates 
    int dailyprice =0; 
    ifstream myfile("stockdatabase.txt"); // open textfile 

    int i,j; 
    for(i=0;std::getline(myfile,myline);i++) // looping thru the number of lines in the textfile 
    { 
     date[i] = stockpile[i].datepurchased; // stockpile.datepurchased give the date,already seperated by : 
     cout<<date[i]<<endl; // prints out date 

     for(j=i+1;std::getline(myfile,myline);j++) 
     { 
      if(date[i] == date[j]) // REFER TO //PROBLEM// BELOW 
       dailyprice += stockpile[i].unitprice; // trying to add the total price of the same dates and print the 
          // datepurchased(datepurchased should be the same) of the total price 
          // means the total price purchased for 9oct16 
     } 
    } 
    cout<<endl; 
} 

一切都是由已檢索和與分隔:從方法我已經寫了

stockpile[i].unitprice將打印出的價格

stockpile[i].itemdesc將打印出來的物品描述

問題

我想總結相同日期的單位價格。並顯示總單價+日期 如u可以看到我的文本文件,

,如果我做了以上如果date[i] == date[j]聲明,但它不會工作,因爲如果有什麼其他的9oct別的地方?

我的文本文件是:

itemid:itemdesc:unitprice:datepurchased 

22:blueberries:3:9oct16  
11:okok:8:9oct16  
16:melon:9:10sep16  
44:po:9:9oct16  
63:juicy:11:11oct16 
67:milk:123:12oct16  
68:pineapple:43:10oct16 
69:oranges:32:9oct16 <-- 

不C++在把數組對象在那裏我可以做到這一點:

testArray['9oct16'] 

//編輯//試圖Ayak973的答案,連克編譯後++ -std = C++ 11 Main.cpp

Main.cpp: In function ‘void displaydailyreport()’: 
Main.cpp:980:26: error: ‘struct std::__detail::_Node_iterator<std::pair<const std::basic_string<char>, int>, false, true>’ has no member named ‘second’ 
       mapIterator.second += stockpile[i].unitprice; 

回答

2

用C++ 11的支持,您可以使用std :: unordered_map來存儲鍵/值對:

#include <string> 
#include <unordered_map> 

std::unordered_map<std::string, int> totalMap; 

//... 

for(i=0;std::getline(myfile,myline);i++) { 
    auto mapIterator = totalMap.find(stockpile[i].datepurchased); //find if we have a key 
    if (mapIterator == totalMap.end()) { //element not found in map, add it with date as key, unitPrice as value 
     totalMap.insert(std::make_pair(stockpile[i].datepurchased, stockpile[i].unitprice)); 
    } 
    else { //element found in map, just sum up values 
     mapIterator->second += stockpile[i].unitprice; 
    } 
} 

之後,你有一個地圖日期鍵和單價的總和作爲值。要獲得這些值,您可以根據for循環使用範圍:

for (auto& iterator : totalMap) { 
    std::cout << "Key: " << iterator.first << " Value: " << iterator.second; 
} 
+0

我必須做的G ++ -std = C++ 11 Main.cpp的編譯,這讓我編譯錯誤,看到我的編輯@ Ayak973 – what

+0

@ user2601570 :我的不好,我沒有測試代碼,我編輯了我的文章,只是使用'mapIterator-> second' – Ayak973

+0

謝謝,但它從文本文件的最後一行打印出來,它假設以這種方式工作? – what