C ++解释器:如何发出错误消息? [英] C++ Interpreter: How to emit error messages?

查看:91
本文介绍了C ++解释器:如何发出错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像现在所有解释器一样发出动态错误消息,例如:

I want to emit dynamic error messages like all interpreters do nowadays, for example:

Name error: Undefined variable

将是常数,但我想达到的是:

would be constant, however what I want to reach is:

Name error: Undefined variable 'X', in line 1


$ b b

好吧。行号真的没有问题:每个错误消息必须有一个行号,所以我将它添加到错误发射器函数:

Okay. The line number was really no problem: Every error message must have a line number, so I added it to the error emitter function:

Error( ErrType type, string msg, int line );

那么我的问题在哪里?

如何获得'X'未定义的变量*


  • 我不能使用sprintf,因为它不支持字符串,但我到处都使用它


  • 我希望将所有内容都放到一个函数中,如上所述, Error()

  • I can't use sprintf as it doesn't support strings yet I use them everywhere
  • I can't simply use cout and connect everything as I want error messages to be supressable
  • I'd like to get everything into one function like above, Error()

如何组合动态错误讯息?

例如:错误(名称,sprintf(未定义变量%s,myVariableName),lineNum);

(但 myVariableName 是一个字符串, sprintf p>

(But myVariableName is a string and sprintf will mess things up)

推荐答案

通过调用可以从 myVariableName 中获得一个以null结尾的C字符串 c_str

You can get a null-terminated C string out of myVariableName by calling c_str:

myVariableName.c_str()

请注意,您使用 sprintf sprintf 的第一个参数获取放置格式化字符串的缓冲区。如果你在程序中使用 std :: string ,为什么要使用 sprintf ?如果错误需要 std :: string ,那么您只需使用字符串连接:

Note that your use of sprintf is incorrect; the first parameter of sprintf takes the buffer into which to place the formatted string. If you are using std::string in your program, why use sprintf at all? If Error takes a std::string then you can just use string concatenation:

Error(Name, "Undefined variable " + myVariableName, lineNum);

这篇关于C ++解释器:如何发出错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆