如何在字符串末尾添加零

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

本文关键字:添加 字符串      更新时间:2023-10-16

我正在尝试从一个名为"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 射线光谱²²²²┘

只需为您的数组再分配 +1 char,但不要读取该char,只需将其设置为 0

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

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

C++ 中将整个文件读入 std::string 的最佳方法是什么?

我现在用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, '');
    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);
}