我正在尝试获取一个文本文件,其中包含从当天多个点获取的“股票市场行情”。
即:
股票价格
HPQ 121
MSFT 76
X 133
易趣92
XOM 64
AAPL 141
道指128
AAPL 130
ABC 139
ABC 102
道指121
HPQ 121
道指96
XOM 130
MSFT 132
HPQ 129
HPQ 71
谷歌142
MSFT 67
X 70
我需要获取这些值,删除重复项并按字母顺序显示结束值。到目前为止我有这个...
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
using namespace std;
int main()
{
string filename;
map<string, int> string_count;
vector<string> market_list;
ifstream data_store;
//cout << "Enter stock file name to analyze" << endl;
//cin >> filename;
//data_store.open(filename.c_str());
data_store.open("stock1.txt");
while(!data_store.eof())
{
string element;
//data_store >> element;
getline(data_store, element);
//Remove ticker price from list
if(element != "Ticker Price")
{
string_count[element]++;
}
}
map<string, int>::iterator map_iter;
for(map_iter = string_count.begin(); map_iter != string_count.end(); map_iter++)
{
market_list.push_back(map_iter->first);
}
data_store.close();
ofstream output_file;
output_file.open("stock_result.txt");
output_file << "Latest prices: " << endl;
vector<string>::iterator iter;
for (iter = market_list.begin(); iter != market_list.end(); iter++)
{
string the_element = *iter;
int num_times_repeated = string_count[the_element];
for(int x = 0; x< num_times_repeated; x++)
{
output_file << the_element << endl;
}
}
output_file.close();
}
按字母顺序输出文件的所有值,而不删除任何内容。我明白这是为什么,但我很难解决如何将其设置为我想要的。请记住,我是一名学生,所以我不需要直接的答案:)
编辑
我希望我的代码接受上面的列表并输出“结束”值,这是每个代码的最终值并按字母顺序显示它们
所以结果是
最新价格:
ABC 102
AAPL 130
道指96
等等。
最佳答案
std::map<std::string,int> stocks;
std::string symbol, line;
int value;
while (getline(data_store,line))
{
std::istringstream iss(line);
if (iss >> symbol >> value)
stocks[symbol] = value;
}
然后只需对股票进行迭代器即可。
关于c++ - 我需要帮助了解如何在 C++ 中对包含多个带空格的字符串的集合或 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12946867/