压缩此代码片段 c++
Condense this code snippet c++
我的代码正常运行,但我正在寻找更优雅的解决方案
在这个 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()
您可以修改流的空格分类,引入"流提取器"(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();
}
尝试使用 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);
}
相关文章:
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- Opengl 3.1 GLSL 140 在 C++ 年输出白色在片段着色器中
- 这两个代码片段相似,但显示的结果不同
- 如何替换此示例代码片段中已弃用的handler_type_t或 boost::asio::handler_type?
- 我需要解释给定片段的输出
- 如果我在下面的代码片段中添加"delete[] d;",为什么我得到零?
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- 任何人都可以解释一下我是否需要 & 在第一个代码片段中
- OpenGL 片段着色器未在英特尔 HD 4000 显卡上编译
- 帧缓冲纹理变为白色(片段着色器不会影响它)
- 如何在 c++ 中检查连续片段中数字被 11 整除
- 提取狮身人面像文档中的C++代码片段
- 为什么此代码片段有效?如何取消引用空点?
- 将顶点位置从顶点传递到片段着色器 - 仅在使用 Nsight 进行调试时有效
- 无法在这个基本的Qt代码片段中找到错误,但我被告知它肯定存在?
- 使用片段着色器写入 1D 纹理后从 1D 纹理读回不起作用
- 如何在顶点着色器中使用VBO数据作为位置数据,在片段着色器中使用统一数据作为颜色数据
- 这个代码片段中会发生死锁吗?为什么
- 同时与两个片段着色器发生碰撞
- 这个片段中关于 n 在 pc[i] 中的表示发生了什么