【发布时间】:2020-10-07 07:52:32
【问题描述】:
#include<bits/stdc++.h>
using namespace std;
int main()
{
char *one;
one = new char[1];
cin.getline(one, 5);
cout<<one<<endl;
return 0;
}
这应该为字符指针 *one 分配 1 个字节空间或 1 个字符空间。现在我使用 cin.getline 输入 5 个字符,为什么它只输出前 4 个字符而不是 5 个?以及为什么它只输出 1 个字符,因为我只分配了 1 个字符空间?
我尝试过使用
for(int i = 0; one[i] != '\0'; ++i) cout<<one[i];
它做同样的事情,它输出我输入的前 4 个字符,而不是 5 个字符。我希望它只存储 1 个字符,因为我只分配了 1 个字节空间。
【问题讨论】:
-
我想你很困惑。
getline不会重新分配您的 char 数组。它甚至不知道它是如何分配的。请改用std::string,或分配足够的字节来存储字符和字符串终止符。 -
此外,请避免使用
<bits/stdc++.h>和using namespace std。第一个是不标准的,第二个是不好的做法。 -
您遇到了未定义的行为。 “未定义”意味着它可以是任何东西,包括“看起来工作正常”、“格式化你的 C 盘”或“making demons fly out of your nose”
-
@AmanJain paddy 是对的,两者都应该避免,见这里:Why should I not
#include <bits/stdc++.h>。 Why isusing namespace std;considered bad practice? -
using namespace std 将 数千个 名称带入范围,尤其是当您包含 gcc 的“everything std”标头时
标签: c++ string char codeblocks