Question

I'm building a simple interpreter of a language that i'm developing, but how i can do a cout of something that is after a word and in rounded by "", like this:

#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;
}

And how i can remove the "" when printing the text. Here is the file example:

print "Hello, World"

Read my post in the middle of the answers!

Thanks

Was it helpful?

Solution

I'm assuming what you want is to identify quoted strings in the file, and print them without the quotes. If so, the below snippet should do the trick.

This goes in your while(!file.eof()) loop:

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

OTHER TIPS

I hope this simple example would help.

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

This code finds the first occurnce of ". Then finds the next occurrence of it after the first one. Finally, it extracts the desired string between "" and prints it.

I don't understand your problem. On input of

print "Hello, World"

your test of linha == "print" will never be true (as linha contains the rest of the line so the equalitry is never true).

Are you looking for help on string processing, i.e. splitting of the input line?

Or are you looking for regular expression help? There are libraries you can use for the latter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top