文件分析器-如何读取行
File Parser - How to Read Lines
我正试图在OpenGL中从stdin实现一个行扫描转换,该转换列出了行端点,如下所示:
L 0, 0, 150, 150
C 200 300
L -20, 40, 22, 55
[...]
Z
其中,[…]基本相同,Z字符是一个方便的终止运算符,尽管文件结尾也可以。L和C表示将分别用于绘制线/圆的点/数据集。
以下是我正在进行的解析器(包括所有正在使用的函数的库):
void parseFile ()
{
ifstream lines;
lines.open("C:/Users/Me/Desktop/lines.txt");
string currentLine = 0;
while(getline(lines, currentLine))
{
switch(currentLine[0] = 'L')
{
string coordLine = currentLine.substr(1, currentLine.length());
while (getline(lines, coordLine, ',')){
for(int i = 0; i < coordLine.length(); i++) {
char* c = 0;
*(c+i) = coordLine[i];
atoi(c);
cout << c;
}
return;
}
}
switch(currentLine[0] = 'Z') {
break;
}
switch(currentLine[0] = 'C') {
//Similar implementation to line case when resolved
}
}
}
我试图将整数值(无逗号和L/C/Z分隔符)读取到数组中,这样我就可以简单地使用它们在OpenGL中绘图。然而,我在阅读和储存方面遇到了一些困难。正如你所看到的,我的算法方法是根据行首的字母字符进行切换,然后将字符串减少到剩余值,并尝试处理它们。然而,我在尝试将我定义的坐标线中的值转换为整数时遇到了困难。
简而言之,我的问题是:我的方法有意义吗?有什么可能比我计划实现的单独阵列方法更简单的方法来存储这些坐标以供OpenGL绘图使用?最后,如何将文件中的行转换为适当的整数进行存储?
当前代码存在许多问题。我提供了一个如何解析的例子:
void parseFile()
{
ifstream lines;
lines.open("test.txt");
string currentLine; // Do NOT make this = 0 it will cause a crash!
while(getline(lines, currentLine))
{
// no need to process blank lines
// this also fixes potential crash
// when you check the first character
if(currentLine.empty())
continue;
// recommend std::stringstream for parsing strings
std::istringstream iss(currentLine); // turn line into stream
char type; // L, C or Z
if(!(iss >> type)) // ALWAYS check for errors
continue;
// Your switch was incorrectly formed
switch(type)
{
case 'L':
{
char comma;
int x0, y0, x1, y1;
// read the numbers skipping the commas
if(!(iss >> x0 >> comma >> y0 >> comma >> x1 >> comma >> y1))
{
// ALWAYS check for errors
std::cerr << "ERROR: Failed to read L: " << currentLine << std::endl;
continue;
}
// do something with coordinates (x0, y0, x1, y1) here
std::cout << "(" << x0 << ", " << y0 << ", " << x1 << ", " << y1 << ")" << 'n';
break;
}
case 'C':
{
break;
}
case 'Z':
{
break;
}
default:
std::cerr << "ERROR: Unrecognized type: " << currentLine << std::endl;
}
}
}
注意:不要把错误检查当作事后考虑。
希望能有所帮助。
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- C++ 读取文件读取文件不正确
- 如何让我的CSV文件读取器读取C 中的不同类型
- 从文件读取时读取访问冲突
- 从文件读取不读取字符串流
- 读取错误-读取时无限
- 以较小、更频繁的读取或较大的读取方式读取输入
- 从内存到硬盘驱动器(C/ c++)读取和读取整个数组
- FFMPEG自定义读取功能读取所有数据
- 对从文件中读取和读取结构中的结构感到困惑
- 读取、读取、获取和获取行之间有什么区别?