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

Val*_*Val 2 c++ string stringstream

我用C++编程,我不知道如何实现以下功能:

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

这是为了创建一个解释器.我将尝试解释的代码是(即):

10 PRINT A
20 GOTO 10
Run Code Online (Sandbox Code Playgroud)

这只是一个快速示例代码.现在,值将首先存储在"地图"结构中,并在以后将"解释"所有内容时进行访问.要存储的值是:

int lnum //行号

string cmd //命令(PRINT和GOTO)

string exp // expression(在这种情况下为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;
}
Run Code Online (Sandbox Code Playgroud)

我希望这很清楚.

谢谢您的帮助.

瓦莱里奥

pes*_*669 10

std::stringstream假设您已经知道类型,则可以使用a 来拉取令牌.

对于翻译,我强烈建议使用实际的解析器而不是编写自己的解析器.Boost的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;

Run Code Online (Sandbox Code Playgroud)