0

Problem description:

I want to have this effect. I am using C++ to read an input file. I want to design my input file in this way:

....blahblah.....
Define Length 20
Node ($Length 0.1 0.1)
....blahblah.....

So that $Length will be automatically replaced as 20.

I am thinking for a more general situation: such as given an arbitrary string

Node ($strLengthUnknown 0.1 0.1)

I would first split the total string into words and then find if some words start with $ sign and then do the replacement.

My question:

I am wondering is there any smarter way? And I don't want to reinvent the wheel. So if you know there is a better way/library that already can do it, would you please let me know. Thanks

Daniel
  • 2,576
  • 7
  • 37
  • 51

2 Answers2

1

You can split the string - and this question has been asked many times: Split a string in C++? Then, you can search for words and do the replacement.

However, the simpler approach will be to search for the '$' sign and check if it the previous character before '$' is something that does not belong to word - whitespace or a bracket in your example. I don't the whole grammar of your files, but in the case when we're looking for identifiers starting with a letter, checking the next character after '$' will be sufficient.

    string x = "Node ($Length 0.1 0.1)";
    size_t len = x.length();
    size_t pos = 0;
    while((pos = x.find("$",pos)) != string::npos) {
        if(pos == 0 || isspace(x[pos-1]) || x[pos-1] == '(') {
            if(pos != (len -1) &&  isalpha(x[pos+1])) {
                //find the length of word, starting from pos
                //do the replacement, update pos
                x.replace(pos,word_length,string_to_replace);
                pos += word_length;
            } else {
                ++pos;
            }
        } else {
            ++pos;
        }
    }
Community
  • 1
  • 1
mcopik
  • 341
  • 2
  • 6
1

I suggest you look at an existing utility to preprocess your file before it is used as input to your application. One such possibility is the C Preprocessor itself. You may be able to use standard Preprocessor directives in your file then run the file through the Proprocessor and then use the output of the Preprocessor.

This would depend on the actual text of the input file and whether there might be problems with the C Preprocessor interpreting some of the text in the input file as a Preprocessor directive.

C Processor as independent tool which also provides some alternatives.

Or Using the C Preprocessor for languages other than C.

Community
  • 1
  • 1
Richard Chambers
  • 16,643
  • 4
  • 81
  • 106