The*_*nda 0 c++ cygwin netbeans char
问候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;
}
Run Code Online (Sandbox Code Playgroud)
实际上让我烦恼的是它给出的输出.
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!
Run Code Online (Sandbox Code Playgroud)
我真的不知道那里发生了什么.更重要的是,如果我添加"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;
Run Code Online (Sandbox Code Playgroud)
输出变化甚至更奇怪的事情
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!
Run Code Online (Sandbox Code Playgroud)
可能是我是愚蠢的东西,但如果我甚至不能使最基本的东西工作,我就无法进步.对不起,如果在某个时候已经回答了同样的问题,请尽力搜索但没有成功.所以你很乐意指出我在哪里愚蠢吗?谢谢.
PS我使用NetBeans 8和Cygwin在Win7x64m下.
该变量Thing只是一个字符的数组.写一个以上的字符会写出界限并导致未定义的行为.
空字符串文字""是单个字符的数组,即字符串终止符,编译器将使用它来初始化数组Thing作为精确副本.
你基本上有两个解决方案,要么声明数组有更大的尺寸:
char Thing[128] = "";
Run Code Online (Sandbox Code Playgroud)
或者您使用标准C++字符串类:
std::string Thing;
Run Code Online (Sandbox Code Playgroud)
我绝对推荐后一种解决方案.