[英]How can I add a zero at the end of a string?
我正在嘗試從名為“ 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] = '\0';
cout << buffer << endl;
或者,根本不使用char[]
,而是使用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, '\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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.