如何在字符串末尾添加零
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] = ' ';
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);
}
相关文章:
- 重载加法运算符(使用函数向对象添加字符串)
- 在不使用内置库函数的情况下添加字符串,我做错了什么?
- 添加字符串和文字(C++)
- 添加字符串类型的类成员会导致调用基类函数而不是子函数
- 添加字符串向量和不同数据类型向量的映射
- 在链接列表中添加字符串的简单方法
- 列表框中的添加字符串 (MFC)
- 添加字符串和文字,顺序如何影响是否可以正确添加字符串
- 向矢量集添加字符串时出现问题<string><>
- 在C++中添加字符串和文字时出现问题
- free():添加字符串时指针无效
- 为什么通过添加字符串文字和char初始化时,为什么不打印字符串
- 矢量尝试添加字符串时会崩溃
- 在数组 C++ 中添加字符串
- 如何添加字符串
- 从向量中删除和添加字符串
- 添加字符串和列表到c++中的映射
- 添加字符串变量后的两个不同的双值
- 为什么我的非所有者绘制的列表框在添加字符串后会出现绘图问题
- 当试图向结构中添加字符串时,程序中断