2017-06-28 27 views
-3

我写只有一个关键字是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 

我能做些什么?有任何想法吗?

+0

解决此类问题的正确工具是您的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,你应该[编辑]你的问题,以包含一个[Minimal,Complete,and Verifiable](http://stackoverflow.com/help/mcve)例子来重现你的问题,以及你在调试器中所做的观察。 –

+0

调试器没有提供任何错误 –

+0

当您逐行检查代码时,有哪些变量值?还'字符串标记[];'看起来不对,甚至编译? –

回答

0

我认为它应该是skipws而不是noskipws,因为当它遇到“write”和“hello”之间的空白时你不处理这种情况;特别是你不清除tok,所以下一个循环它仍然认为这个标记是一个空格。

+0

thnx boiit工作 –

+0

thnx非常非常 –

+0

@GameplayerXd没问题 – meowgoesthedog