cout 时字符串上的额外字符
Extra characters on cstring when cout
我有一个char[4] dataLabel
,当我说
wav.read(dataLabel, sizeof(dataLabel));//Read data label
cout << "Data label:" <<dataLabel << "n";
我得到输出Data label:data�
但是当我循环遍历每个字符时,我得到了正确的输出,应该是"数据"。
for (int i = 0; i < sizeof(dataLabel); ++i) {
cout << "Data label " << i << " " << dataLabel[i] << "n";
}
大小返回 4。我对问题是什么不知所措。
编辑:更让我困惑的是,在我的程序早期基本上相同的代码可以完美地工作。
ifstream wav;
wav.open("../../Desktop/hello.wav", ios::binary);
char riff[4]; //Char to hold RIFF header
if (wav.is_open()) {
wav.read(riff, sizeof(riff));//Read RIFF header
if ((strcmp(riff, "RIFF"))!=0) {
fprintf(stderr, "Not a wav file");
exit(1);
}
else {
cout << "RIFF:" << riff << "n";
这将按预期打印RIFF:RIFF
。
字符数组上缺少空终止符。尝试将其设为 5 个字符,并将最后一个字符设为"\0"。这让程序知道您的字符串已完成,而无需知道大小。
什么是以空结尾的字符串?
char const*
的std::ostream
的 operator<<
重载需要以空结尾的字符串。你给它一个 4 个字符的数组。
请改用标准库string
类:
std::string dataLabel;
请参阅 istream::read 的文档;它不会附加空终止符,而是告诉它正好读取 4 个字符。 正如其他人所指出的,<<
运算符正在寻找一个空终止符,因此它会继续读取数组的末尾,直到找到一个。
我同意另一个建议的答案,即使用std::string
而不是char[]
。
您的char[]
数组不是以 null 结尾的,但接受char*
输入的 <<
运算符需要 null 终止符。
char dataLabel[5];
wav.read(dataLabel, 4); //Read data label
dataLabel[4] = 0;
cout << "Data label:" << dataLabel << "n";
变量 dataLabel 的定义如下
char[4] dataLabel;
它只有四个字符在语句中填充了字符 { 'd'
, 'a', 't', 'a' (wav.read(dataLabel, sizeof(dataLabel));//
因此,当此字符数组的参数是字符数组时,此字符数组没有operator <<
所需的终止零。
因此,在此声明中
cout << "Data label:" <<dataLabel << "n";
该程序具有未定义的行为。
将其更改为
std::cout << "Data label: ";
std::cout.write( dataLabel, sizeof( dataLabel ) ) << "n";
相关文章:
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 如何组合一个宽字符字符串,中间插入一些空字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- 如何将字符字符串用作数学运算符
- 将 Unicode 字符/字符串写入文件
- C++,字符* 字符串修改
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- strcpy正在复制sth字符i字符串.如何解决此错误
- 在C++中将双精度转换为字符*/字符串
- C 中的宽字符字符串
- 如何提取C 中的字符/字符串之间的字符串
- 无法将字符/字符串转换为int
- 带有指针的反转字符字符串
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数