Sea*_*148 0 c++ arrays codeblocks
我正在使用带有 GCC 编译器的代码块来输出包含数组的字符串,但是在打印字符串后,会在字符串末尾输出一个随机字符(每次构建和编译程序时字符都会发生变化)。
我的代码:
#define BUF_SIZE 10
char buf[BUF_SIZE];
char a = 'a';
for (int i=0; i<BUF_SIZE; ++i)
{
buf[i]= a;
a++;
}
string s = buf;
cout << '[' << s << ']' << endl;
Run Code Online (Sandbox Code Playgroud)
输出:
[abcdefghij"
]
Run Code Online (Sandbox Code Playgroud)
我还想知道为什么右方括号位于新行上。我预计输出只是“[abcdefhij]”。我想知道为什么会发生这种情况。
在 C++ 中,当您使用字符数组作为字符串时,它必须以 null 结尾(以 '\0' 结尾),以便我们知道它有多长。尝试更改char buf[BUF_SIZE]为并在循环后char buf[BUF_SIZE+1]添加。buf[BUF_SIZE]='\0'