我的代码功能正常,但我正在寻找更优雅的解决方案
在这个for循环中,我正在从一个文件中解析一行文本,其中数据成员用逗号分隔。这已存储在vector<str>str
文件:
bob,1,2,3
sally,5,8,6
joe,5,1,9
我需要将名称和3个相应的分数分别存储到vector<student> s
的相应分区中。
有什么方法可以进一步浓缩这个吗?
for (string currLine : str)
{
int pos = 0;
int next = 0;
next = currLine.find (',', pos);
string name (currLine.substr (pos, next));
pos = next + 1;
next = currLine.find (',', pos);
string expr (currLine.substr (pos, next));
int a = atoi (expr.c_str());
pos = next + 1;
next = currLine.find (',', pos);
expr = (currLine.substr (pos, next));
int b = atoi (expr.c_str());
pos = next + 1;
next = currLine.find (',', pos);
expr = (currLine.substr (pos, next));
int c = atoi (expr.c_str());
student s (name, a, b, c); //create student with extracted name and scores
vec.push_back (s); //now push this student onto the vector
}//end for()
答案 0 :(得分:0)
尝试使用fstream和提取运算符。您可以轻松地将输入存储到单个变量中。
#include <fstream>
.
.
.
// declare variables
fstream fin( "fileName.txt", ios::in );
string name;
char comma;
int a, b, c;
// loop until the end of the file
while(!fin.eof())
{
// get one line of data from the file
fin >> name >> comma >> a >> comma >> b >> comma >> c;
// add to your datatype
student s (name, a, b, c);
// push into your vector
vec.push_back (s);
}
答案 1 :(得分:0)
您可以修改流的空白分类,引入“流提取器”(operator>>()
),并使用std::istream_iterator<student>
插入到矢量中。以下是您的程序的示例:
#include <iostream>
#include <vector>
#include <iterator>
class student_fmt;
struct student
{
student() = default;
student(std::string const& name, std::string const& a,
std::string const& b, std::string const& c)
: m_name(name)
, m_a(a)
, m_b(b)
, m_c(c)
{ }
friend std::istream& operator>>(std::istream& is, student& s)
{
if (std::has_facet<student_fmt>(is.getloc()))
{
is >> s.m_name >> s.m_a >> s.m_b >> s.m_c;
}
return is;
}
void display() const
{
std::cout << m_name << m_a << " " << m_b << " " << m_c << '\n';
}
private:
std::string m_name, m_a, m_b, m_c;
};
class student_fmt : public std::ctype<char>
{
static mask table[table_size];
public:
student_fmt(size_t refs = 0) : std::ctype<char>(table, false, refs)
{
table[static_cast<int>(',')] |= space;
}
};
student_fmt::mask student_fmt::table[table_size];
int main()
{
std::cin.imbue(std::locale(std::cin.getloc(), new student_fmt));
std::vector<student> v(std::istream_iterator<student>(std::cin), {});
for (auto& c : v)
c.display();
}