简体   繁体   中英

What is the best, cross platfrom, way to parse a text file?

I would like to port my Windows code to native C++ and need to get rid of all CLI code. I found .NET very helpful in parsing textual input but when I started re-writing it in C++ I was still wont to code in C with fseek and char * in place of String . Finding C++ has a string type in the std namespace I opened up my STL documentation (from a zip archive) and found "string_discussion.html" which began, "Strings in SGI STL" and continued to describe an oversight potentially causing intermittent errors.

Is std::string safe? What is the relationship of std to STL if any? Is C file IO that dangerous and C++ stream and string IO so much better?

The issues described in the document exist for some compilers, notably MSVC, but I've never run into an actual problem in the real world. The GNU compilers implement the described "unshareable" strings, that is, using non-const operator[] makes the string unshareable and creates a copy if required.

The STL classes are, by definition, not threadsafe and need to be surrounded by locks if accessed from multiple threads; I think that this is a feature as it makes them significantly faster and allows for the implementation of lock-free algorithms.

The relation between std and the STL is basically that the STL has been integrated into the C++ standard library which lives in the std namespace. The standard has evolved since, but remains largely compatible.

In general it is safe for use in text parsers: a typical pattern for line-by-line parsing is

std::istream &is;
for(std::string line; getline(is, line);)
{
    // parse line
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM