0

I have a simple text file of about 30 lines, as follows:

A 45.0 X 250.0  
Y -23.8
A 22.0 X -1016.0
Y 4.9
L 0
M 16.1 T 0 N 0

...etc...
...etc...

Every line contains 1 to 3 pairs of a capital letter and a float. All separators are spaces.
I then made a program which checks every single line of that file with this simple regex:

std::ifstream stream;
try
{
    stream.open("/ArchivioProgrammi/p1.prg", std::ios::in);
}
catch(std::exception& e)
{
    std::stringstream st;
    st << "Error opening file.\nError:   " << e.what();
    throw MyLoadException(st.str());
}
std::string line;
unsigned int lineCount = 0;

while(std::getline(stream, line))  //  Per ogni linea del file estraggo fino a 6 token
{
    if(line.length() == 0) continue;

    /***  This "if" hangs indefinitely!!  ***/
    if(!std::regex_match(line, std::regex("([A-Z] [\\-\\+]?[0-9]+(\\.[0-9]+)?)( [A-Z] [\\-\\+]?[0-9]+(\\.[0-9]+)?){0,2}")))
    {
        std::stringstream st;
        st << "Line #" << lineCount << " is invalid.";
        throw MyLoadException(st.str());
    }

    //  Tokenize the line and do something with the tokens...

    ++lineCount;

}

if(stream.eof())
{
    stream.close();
}

Whenever the control reaches the if, the programs hangs forever! Unresponsive interface, no errors, no false or true! Why?

I'm developing with KDevelop under OpenSuse latest version.

Ernesto_Che
  • 67
  • 2
  • 8

2 Answers2

0

Using raw string it works like a charm. Even if I have never understood the meaning of beginning such strings with both double quotes and a parenthesis....

How coud I have written the regex in a shorter form?

Ernesto_Che
  • 67
  • 2
  • 8
0

Try confirming that your regex pattern is correct by testing it online (e.g. online Regex tester). You may also want to consider iterating through the input file line by line using regex on one line at a time. Or just not use regex at all.

Cogitator
  • 154
  • 1
  • 1
  • I'm not sure of what yo're advising. Going line by line? That's exactly what I said I'm doing! – Ernesto_Che Feb 13 '18 at 20:32
  • Sorry - I see from your code that you are reading line by line. I also tested your regex pattern and it does find matches in your text file. Start commenting out your code (e.g. if(!std::regex_match) until you find what is making it hang. Hope you solve it. – Cogitator Feb 20 '18 at 22:29