C++ 字符串-C+之后显示的随机字符+;
我使用GCC编译器的代码块来输出一个包含数组的字符串,但是在打印字符串之后,在字符串的末尾会输出一个随机字符(每次我构建和编译程序时,字符都会发生变化) 我的代码:C++ 字符串-C+之后显示的随机字符+;,c++,arrays,codeblocks,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 <&
#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;
我还想知道为什么结束方括号是在一个新的行。我希望输出只是“[abcdefhij]”。我想知道为什么会发生这种情况在C++中,当使用字符数组作为字符串时,必须终止null(用‘0’结尾),这样我们就知道它有多长。尝试将
char-buf[buf\u SIZE]
更改为char-buf[buf\u SIZE+1]
,并在循环后添加buf[buf\u SIZE]='\0'
。char
字符串实际上只是C样式的空终止字符串。添加'\0'
以终止它:
#include <iostream>
#include <string>
using namespace std;
int main() {
const size_t BUF_SIZE = 10; // consider size_t
char buf[BUF_SIZE + 1]; // +1 to make room for '\0'
char a = 'a';
for (int i = 0; i < BUF_SIZE; ++i)
{
buf[i] = a;
a++;
}
buf[BUF_SIZE] = '\0'; // null terminate it
string s = buf;
cout << '[' << s << ']' << endl;
return 0;
}
如果您只想在字符串tho中添加char
s,您可以直接在字符串上使用push_back
:
#include <iostream>
#include <string>
using namespace std;
int main() {
const size_t BUF_SIZE = 10;
string s = "";
char a = 'a';
for (int i = 0; i < BUF_SIZE; ++i)
{
s.push_back(a++); // increments a and returns the previous value
}
cout << '[' << s << ']' << endl;
return 0;
}
buf[BUF_SIZE] = 0;
#包括
#包括
使用名称空间std;
int main(){
常数大小为10;
字符串s=“”;
字符a='a';
对于(int i=0;i coutC字符串以null结尾,这意味着它们以0值结尾
在这种情况下,如果要输出字母表的前10个字符,则需要考虑此空终止字符
有几种方法可以做到这一点,但首先需要考虑缓冲区中的额外字符:
#define BUF_SIZE 10
char buf[BUF_SIZE + 1];
根据编译器的不同,此缓冲区内存可能已初始化为0,但最好不要进行假设
将缓冲区的最后一个值设置为0,以终止字符串:
#include <iostream>
#include <string>
using namespace std;
int main() {
const size_t BUF_SIZE = 10;
string s = "";
char a = 'a';
for (int i = 0; i < BUF_SIZE; ++i)
{
s.push_back(a++); // increments a and returns the previous value
}
cout << '[' << s << ']' << endl;
return 0;
}
buf[BUF_SIZE] = 0;
然后,您可以继续执行已经编写的其余代码,只需将char数组作为字符串输出即可
char a = 'a';
for (int i=0; i<BUF_SIZE; ++i) {
buf[i]= a;
a++;
}
cout << '[' << buf << ']' << endl;
chara='a';
对于(In i=0;Iye似乎忘记了C++中的代码> char < /Cord>字符串实际上是NoLead终止字节串。这个空终止位非常重要。而且,如果您打算将C样式的空终止字节串复制到C++ <代码> STD::String < /Cord>对象,为什么不直接将字符追加到<代码> S/<代码>?是否属于buf
?