Search code examples
c++visual-studio-2017

How can I add a zero at the end of a string?


I'm trying to read some text out of a file called "file.dat". The problem is, that the string in the file does not include a zero at the end as for standard C. So I need something that adds the zero, so I can work with the string without getting random symbols after the string when I print it.

void cSpectrum::readSpectrum(const std::string &filename, double 
tubeVoltage, double &minEnergy, std::string &spectrumName)
{
    //Object with the name "inp" of the class ifstream
    ifstream inp(filename, ios::binary);

    //Checks if the file is open
    if (!inp.is_open()) {
        throw runtime_error("File not open!");
    }

    cout << "I opened the file!" << endl;

    //Check the title of the file
    string title;
    char *buffer = new char[14];
    inp.read(buffer, 14);

    cout << buffer << endl;
}

At the moment I get the following output, I would like to get it without the ²²²²┘.

I opened the file!

x-ray spectrum²²²²┘


Solution

  • I did it with the std::string now. If you want you can replace the 14 by an integer variable.

    void cSpectrum::readSpectrum(const std::string & filename, double tubeVoltage, double 
            & minEnergy, std::string const & spectrumName){
    
        ifstream inp(filename, ios::binary);
    
        //Checks if the file is open
        if (!inp.is_open()) {
            throw runtime_error("ERROR: Could not open the file!");
        }
    
        //Reads the title
        string title(14, '\0');
        inp.read(&title[0], 14);
    
        //If it is not the correct file throw an ERROR
        if (title != spectrumName)
            throw runtime_error("ERROR: Wrong file title");
    
        readSpectrum(inp, tubeVoltage, minEnergy, spectrumName);
    }