C++ ifstream Error Checking

前端 未结 1 1701
清歌不尽
清歌不尽 2020-12-28 15:29

I am new to C++ and want to add error checking to my code plus I want to make sure I\'m using good coding practices. I read a line from an ASCII file into a string using:

相关标签:
1条回答
  • 2020-12-28 16:14

    paramFile >> tmp; If the line contains spaces, this will not read the whole line. If you want that use std::getline(paramFile, tmp); which reads up until the newline. Basic error checking is done by examining the return values. For example:

    if(paramFile>>tmp) // or if(std::getline(paramFile, tmp))
    {
        std::cout << "Successful!";
    }
    else
    {
        std::cout << "fail";
    }
    

    operator>> and std::getline both return a reference to the stream. The stream evaluates to a boolean value which you can check after the read operation. The above example will only evaluate to true if the read was successful.

    Here is an example of how I might make your code:

    ifstream paramFile("somefile.txt"); // Use the constructor rather than `open`
    if (paramFile) // Verify that the file was open successfully
    {
        string tmp; // Construct a string to hold the line
        while(std::getline(paramFile, tmp)) // Read file line by line
        {
             // Read was successful so do something with the line
        }
    }
    else
    {
         cerr << "File could not be opened!\n"; // Report error
         cerr << "Error code: " << strerror(errno); // Get some info as to why
    }
    
    0 讨论(0)
提交回复
热议问题