gpt4 book ai didi

c++ - std::stringstream 从字符串中读取 int 和字符串

转载 作者:太空狗 更新时间:2023-10-29 23:38:14 26 4
gpt4 key购买 nike

我正在用 C++ 编程,但我不确定如何实现以下目标:

我正在将一个文件流复制到内存中(因为我被要求这样做,我更喜欢从流中读取),然后尝试访问它的值以将它们存储到字符串和 int 变量中。

这是创建一个解释器。我将尝试解释的代码是 (ie):

10 PRINT A
20 GOTO 10

这只是一个简单的示例代码。现在,这些值将首先存储在“映射”结构中,然后在“解释”所有内容时访问。要存储的值是:

int lnum//行号

string cmd//命令(PRINT 和 GOTO)

string exp//表达式(在本例中为 A 和 10,但可以包含 (a*b)-c 等表达式)

问题给出了以下代码,我如何访问这些值并将它们存储在内存中?此外,exp 字符串的大小可变(可以只是一个变量或表达式),所以我不确定如何读取它并将其存储在字符串中。

代码:


#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <map>
#include <sstream>

using namespace std;

#include "main.hh"


int main ()
{
int lenght;
char *buffer;

// get file directory
string dir;
cout << "Please drag and drop here the file to interpret: ";
getline (cin,dir);
cout << "Thank you.\n";
cout << "Please wait while your file is being interpreted.\n \n";

// Open File
ifstream p_prog;
p_prog.open (dir.c_str());

// Get file size
p_prog.seekg (0, ios::end);
lenght = p_prog.tellg();
p_prog.seekg(0, ios::beg);

// Create buffer and copy stream to it
buffer = new char[lenght];
p_prog.read (buffer,lenght);
p_prog.close();

// Define map<int, char>
map<int, string> program;
map<int, string>::iterator iter;


/***** Read File *****/
int lnum; // line number
string cmd; // store command (goto, let, etc...)
string exp; // to be subst with expr. type inst.

// this is what I had in mind but not sure how to use it properly
// std::stringstream buffer;
// buffer >> lnum >> cmd >> exp;

program [lnum] = cmd; // store values in map




// free memory from buffer, out of scope
delete[] buffer;
return 0;
}

我希望这是清楚的。

感谢您的帮助。

瓦莱里奥

最佳答案

您可以使用 std::stringstream提取 token ,假设您已经知道类型。

对于解释器,我强烈建议使用实际的解析器而不是自己编写。提升的 XPressive图书馆或 ANTLR工作得很好。您可以在解析语法或简单地构建 AST 时使用语义操作构建解释器原语。

另一种选择是 Flex & Bison .基本上,这些都是用于解析预定义语法的工具。您可以构建自己的,但要做好受挫的准备。递归平衡括号或强制执行运算顺序(例如,先除后乘)并非易事。

原始C++解析方法如下:


#include <sstream>
#include <string>

// ... //

istringstream iss(buffer);
int a, b;
string c, d;

iss >> a;
iss >> b;
iss >> c;
iss >> d;

关于c++ - std::stringstream 从字符串中读取 int 和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1883056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com