【发布时间】:2017-06-28 09:36:00
【问题描述】:
我正在编写一种只有一个关键字 write 的小型编程语言。我没有做过解析器,而是词法分析器。在到达 " 令牌之前它工作正常。
main.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
int main(int argc, char* argv[2])
{
char text;
string tok = "";
string str = "";
vector <string> tokens;
fstream inFile(argv[1]);
while (inFile >> noskipws >> text)
{
tok += text;
if (tok == "write")
{
tokens.push_back(tok);
tok = "";
}
else if(tok == "\"")
{
str += text;
tokens.push_back("String:"+str);
str = "";
tok = "";
tok += text;
}
for (auto const& c : tokens)
std::cout << c << ' ';
}
return 0;
}
test.txt:
write "hello"
输出是:
write write write write write write write ...
而不是,
String:hello
我能做什么?有什么想法吗?
【问题讨论】:
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 edit 您的问题包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
调试器没有报错
-
当您逐行浏览代码时,变量值是什么?
string tokens[];看起来也错了,它还能编译吗? -
删除了还是什么都没有
-
再一次,当您单步执行时,变量值是什么?