如何在c++中从文件中读取string和相应的int
How to read string and corresponding int from a file in C++?
我正在做一个由两部分组成的课程项目,已经完成了第一部分,但在第二部分遇到了麻烦。在第一部分中,我能够从文件中读取一个列表,并将其读取到一个向量中,以便使用各种函数进行操作。这个部分的列表看起来像:
banana
apple
pineapple
grapefruit
orange
pear
grape
lime
lemon
我能够完成。对于第一部分,我有一个字符串向量。然而,第二部分为这些值引入了一个量。这个部分的列表如下:
foo 5
bar 4
baz 2
boz 1
foo 3
在这一点上,我不确定如何读取item作为字符串和后面相应的int。对于重复的项,它们应该加到该项的原始值上。我计划有一个对象的矢量,它有一个名称和一个数量来操纵,但我需要先读取文件。谢谢你的帮助!
这是我最初读取文件
的方式if (fileIn.is_open()){
//file opened successfully so we are here
ifstream inf(fileName + ".txt");
string word;
while (inf >> word)
{
currentSet.push_back(word);
}
就这样做:
map<string, int> vals; //or some other data structure
ifstream ifs(somefile);
string word;
int i;
while(ifs >> word >> i) {
vals[word] += i;
}
简单地一个接一个地读。当然,您可以根据需要添加错误检查。但是我推荐使用map数据结构,以便于访问和操作。
相关文章:
- 如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?
- 两个数组,int 和 string,如何显示带有对应 int 的字符串?
- <string> 如何在使用 SWIG 时将 int 数组和 List 作为参数传递给 C# C++
- OpenCV undefined reference to 'cv::imread(cv::String const&, int)'
- map<string, int> m= {}; 在C++中是什么意思?
- 如何从map<pair<string,int>,pair<string,Array>>中迭代和查找?
- C++将文件行分离为String和Int
- 与 string.size() 比较时 int 的符号性显示警告
- freq_table[field_pm_value] = map<string, int>(); 是什么意思?
- 将 int 附加到 std::string
- 如何在一对集合的向量中插入元素?vector<pair<int,set<string>>>
- 按值对 std::unordered_map<std:::string, std::atomic<unsigned int>> 进行排序
- 在 C++03 中将 std::string 转换为 int
- 方括号在"map <string, int> instance[numberFeatures];"中是什么意思
- 如何使用 c++ 中的 int* count(const string&s)计算字符串中每个数字的出现次数?
- 如果可以将其放在私有中,为什么要使用静态常量(int/string/.)?
- 在字节数组存储中嵌入 int/string
- c++中从double/int/string到bool的自动转换
- c++ string (int) + string (int)
- 如何在int,string类型的映射上使用find