gpt4 book ai didi

c++ - C 错误 "s1, s2 are used uninitialised in this function"

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:38 24 4
gpt4 key购买 nike

这是我在第一节编程基础课后遇到的问题之一

gets() 工作正常(我认为),但“cin”拒绝工作

int main(void)
{
char *s1, *s2;
puts("Enter your name and surname for gets()");
gets(s1);
puts("Enter your name and surname for cin()");
cin >> s2;
cout << s1 << "! Hello from gets" << endl;
cout << s2 << "! Hello from cin" << endl;
return 0;
}

我希望 cin 输出你在控制台中输入的内容,但在输入 programm 后等待一秒钟,然后一切都关闭,根本没有任何输出。

截图是我们老师给的,没用

Screenshot

最佳答案

你的程序有未定义的行为。

gets 需要一个指向足够有效内存以读取和存储输入的参数。在您发布的代码中,s1 不符合该要求。您对 cins2 的使用也存在类似问题。

更重要的是,不要再使用gets。由于安全问题,这是一个已弃用的功能。使用 std::stringstd::getline

int main(void)
{
std::string s1;
std::string s2;

puts("Enter your name and surname");
std::getline(std::cin, s1);

puts("Enter your name and surname again");
std::getline(std::cin, s2);

// Use s1 and s2.
return 0;
}

有用的阅读:Which functions from the standard library must (should) be avoided?

关于c++ - C 错误 "s1, s2 are used uninitialised in this function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57792459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com