cout 时字符串上的额外字符

Extra characters on cstring when cout

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

我有一个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::ostreamoperator<< 重载需要以空结尾的字符串。你给它一个 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";