如何在字符串末尾添加零?

时间:2019-03-27 19:57:33

标签: c++ visual-studio-2017

我正在尝试从名为“ file.dat”的文件中读取一些文本。问题是,文件中的字符串与标准C一样在结尾处不包含零。因此,我需要添加零的内容,这样我就可以使用该字符串,而在打印时该字符串之后不会出现随机符号

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;
}

目前,我得到以下输出,我想在没有²²²┘的情况下得到它。

我打开了文件!

x射线光谱²²²²┘

2 个答案:

答案 0 :(得分:3)

只需为您的数组分配另外+1个char,但不要读入该char,只需将其设置为0

char buffer[15];
inp.read(buffer, 14);
buffer[14] = '\0';
cout << buffer << endl;

或者,根本不使用char[],而是使用std::string,请参见:

What is the best way to read an entire file into a std::string in C++?

答案 1 :(得分:0)

我现在是用std::string做的。如果需要,可以用整数变量替换14。

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);
}
相关问题