【问题标题】:Read Something After a Word in C++在 C++ 中读完一个单词
【发布时间】:2009-11-07 03:38:34
【问题描述】:

我正在为我正在开发的一种语言构建一个简单的解释器,但是我如何才能对一个单词之后并用“”四舍五入的东西进行 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;
}

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

打印“你好,世界”

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

谢谢

【问题讨论】:

  • 我回到了 StackOverflow!

标签: c++ file-io interpreter


【解决方案1】:

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

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);

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

【讨论】:

  • 还没有测试过,但它显然是一个简单的方法。
【解决方案2】:

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

这进入您的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); 
    }       
}

【讨论】:

    【解决方案3】:

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

    print "Hello, World"
    

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

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

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

    【讨论】:

    • 我正在构建自己的解释器,我想这样做:仅显示 linha 上“”中的内容,因为这是我正在开发的语言。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2016-01-18
    • 2011-06-02
    • 2010-10-12
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多