向Stack Overflow社区致意。 我正在尝试从基础知识中学习C ++,并遇到一些奇怪的(至少对我来说)行为。这是我的“你好世界”
#include <iostream>
int main()
{
std::cout << "Enter Thing! " << std::endl;
char Thing[]="";
std::cin >> Thing;
std::cout << "Thing is " << Thing << "!" << std::endl;
int i=0;
while (i <= 10)
{
++i;
std::cout << "Thing is " << Thing << " in " << i << " while!" << std::endl;
std::cout << "i is " << i << "!" << std::endl;
}
std::cout << "Thing is " << Thing << " after while!" << std::endl;
std::cout << "i is " << i << ".5!" << std::endl;
}
实际上让我烦恼的是它给出的输出。
Enter Thing!
thing
Thing is thing!
Thing is t☺ in 1 while!
i is 1!
Thing is t☻ in 2 while!
i is 2!
Thing is t♥ in 3 while!
i is 3!
Thing is t♦ in 4 while!
i is 4!
Thing is t♣ in 5 while!
i is 5!
Thing is t♠ in 6 while!
i is 6!
Thing is t in 7 while!
i is 7!
Thing is in 8 while!
i is 8!
Thing is t in 9 while!
i is 9!
Thing is t
in 10 while!
i is 10!
Thing is t♂ in 11 while!
i is 11!
Thing is t♂ after while!
i is 11.5!
我真的不知道那里发生了什么。更重要的是,如果我添加“for”构造,例如
for (int i=4; i <=7; ++i)
{
std::cout << "i is " << i << "!" << std::endl;
std::cout << "Thing is " << Thing << " for!" << std::endl;
}
std::cout << "i is " << i+3 << ".5!" << std::endl;
std::cout << "Thing is " << Thing << " after for!" << std::endl;
输出更改为更奇怪的事情
Enter Thing!
thing
Thing is thing!
Thing is thing☺ in 1 while!
i is 1!
Thing is thing☻ in 2 while!
i is 2!
Thing is thing♥ in 3 while!
i is 3!
Thing is thing♦ in 4 while!
i is 4!
Thing is thing♣ in 5 while!
i is 5!
Thing is thing♠ in 6 while!
i is 6!
Thing is thing in 7 while!
i is 7!
Thing is thin in 8 while!
i is 8!
Thing is thing in 9 while!
i is 9!
Thing is thing
in 10 while!
i is 10!
Thing is thing♂ in 11 while!
i is 11!
Thing is thing♂ after while!
i is 11.5!
i is 4!
Thing is t♦ for!
i is 5!
Thing is t♣ for!
i is 6!
Thing is t♠ for!
i is 7!
Thing is t for!
i is 14.5!
Thing is after for!
可能是我是愚蠢的东西,但如果我甚至不能让最基本的东西发挥作用,我就无法继续学习。 对不起,如果在某个时候已经回答了同样的问题,请尽力搜索但没有成功。 所以你很乐意指出我在哪里愚蠢吗? 感谢。
P.S。我使用NetBeans 8和Cygwin一起使用Win7x64m。
答案 0 :(得分:5)
变量Thing
是仅包含单个字符的数组。向其中写入多个字符将写出界限并导致未定义的行为。
空字符串文字""
是单个字符的数组,即字符串终止符,编译器将使用它来初始化数组Thing
为精确副本。
你基本上有两个解决方案,要么声明数组有更大的尺寸:
char Thing[128] = "";
或者您使用the standard C++ string class:
std::string Thing;
我绝对推荐后一种解决方案。
答案 1 :(得分:1)
这是有问题的:
char Thing[]="";
您正在创建一个单个字符的空数组,并将用户输入写入其中。
你第一次偶然得到了正确的输出,但随后数据被覆盖了,你得到了这个奇怪的输出。
创建具有足够缓冲区长度的字符串
char thing[256];
或使用字符串对象。
答案 2 :(得分:0)
正如其他人的答案建议的那样,你使用你的char
数组而不是真正初始化它(提供固定大小)。此外,这是C风格的编程。我强烈建议使用C ++ std::string
而不是char
- 数组,因为这不容易出错。
答案 3 :(得分:0)
自编译代码以来,应修复本地声明的此类数组的大小。
char Thing[] = "";
这让你觉得'Thing'的大小是可变的错觉。简而言之,“Thing”的大小将根据右侧给出的初始值自动推断,这会使您输入的字符串写入内存中的意外位置,从而导致未定义的行为。