0

我正在为我正在开发的一种语言构建一个简单的解释器,但是我如何才能对一个单词之后并用“”四舍五入的东西做一个cout ,如下所示:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main( int argc, char* argv[] )
{

 if(argc != 2)
 {
    cout << "Error syntax is incorrect!\nSyntax: " << argv[ 0 ] << " <file>\n";
   return 0;
 }
 ifstream file(argv[ 1 ]);
 if (!file.good()) {
    cout << "File " << argv[1] << " does not exist.\n";
   return 0;
 }
 string linha;
 while(!file.eof())
 {
 getline(file, linha);
 if(linha == "print")
   {
   cout << text after print;
   }
 }
  return 0;
}

以及如何在打印文本时删除“”。这是文件示例:

打印“你好,世界”

在答案中间阅读我的帖子!

谢谢

4

3 回答 3

2

我希望这个简单的例子会有所帮助。

std::string code = " print \" hi \" ";
std::string::size_type beg = code.find("\"");
std::string::size_type end = code.find("\"", beg+1);

// end-beg-1 = the length of the string between ""
std::cout << code.substr(beg+1, end-beg-1);

这段代码找到第".一个出现的然后在第一个之后找到它的下一个出现。最后,它提取所需的字符串""并打印出来。

于 2009-08-01T03:08:20.400 回答
1

我假设您想要的是识别文件中带引号的字符串,并在不带引号的情况下打印它们。如果是这样,下面的代码片段应该可以解决问题。

这在你的while(!file.eof())循环中:

string linha;
while(!file.eof())
{
    getline(file, linha);
    string::size_type idx = linha.find("\""); //find the first quote on the line
    while ( idx != string::npos ) {
        string::size_type idx_end = linha.find("\"",idx+1); //end of quote
        string quotes;
        quotes.assign(linha,idx,idx_end-idx+1);

        // do not print the start and end " strings
        cout << "quotes:" << quotes.substr(1,quotes.length()-2) << endl;

        //check for another quote on the same line
        idx = linha.find("\"",idx_end+1); 
    }       
}
于 2009-08-01T10:26:01.883 回答
0

我不明白你的问题。在输入

print "Hello, World"

你的测试linha == "print"永远不会是真的(因为 linha 包含该行的其余部分,所以等式永远不会是真的)。

您是否正在寻找有关字符串处理的帮助,即分割输入行?

或者您正在寻找正则表达式帮助?您可以将一些库用于后者。

于 2009-08-01T02:42:34.747 回答