【发布时间】:2019-02-05 11:04:26
【问题描述】:
为什么会这样: 我告诉程序我的字符最多有 2 个字符,对吧?
#include <iostream>
#include <string>
using namespace std;
int main() {
char name[2];
cout << "Please, enter your full name: " << endl;
cin.getline(name, 100);
cout << "Hello, " << name << "!\n";
return 0;
}
当我输入 Albert Einstein 时,它运行良好,但这里有 15 个字符,他们怎么能都输入我的变量中,而我的变量应该最多有 2 个字符?
但是使用 getline 我告诉他关联到名称,在这一行中最多写入 100 个字符。
这不起作用:我告诉程序我的字符最多有 1 个字符,对吧?
#include <iostream>
#include <string>
using namespace std;
int main() {
char name[1];
cout << "Please, enter your full name: " << endl;
cin.getline(name, 100);
cout << "Hello, " << name << "!\n";
return 0;
}
当我输入 Albert Einstein 时,它不起作用,但在我创建最多 1 个字符的变量名时看起来很合乎逻辑。
但是使用 getline 我告诉他关联到名称,在这一行中最多写入 100 个字符。
我真正不明白的是,为什么当我创建它并告诉 2 个字符时它可以工作,而当我告诉 1 个字符时它不起作用?
谁能解释一下?
谢谢
【问题讨论】:
-
这是未定义的行为。使用带有大小参数的函数时,您需要跟踪边界。使用
std::string name;和std::getline(std::cin, name);可能会更好。 -
是的,我知道如何解决这个问题,有很多方法可以做到。
-
但我只是想知道为什么 char[1] 不起作用,而 char[2] 却起作用。谢谢你的回答!
-
“通常那里没有什么重要的东西” - 嗯,比如函数返回地址?
-
@FalcoGer C++ 不需要堆栈从任何特定地址开始,堆栈增长可以在任何方向。这里是some examples。
标签: c++