rdu-cpp

杨柳不折
随笔 - 13, 文章 - 0, 评论 - 4, 引用 - 0
数据加载中……

dangerous c-styled func: gets

如果您使用cin來取得使用者的輸入字串,則您會發現輸入字串時中間不能包括空白,如果您想要在輸入字串時包括空白,您必須使用gets()函式,例如:
char str[80];
cout << "輸入字串:";
gets(str);
cout << "輸入的字串:" << str << endl;

使用gets()函式時有一點必須注意,就是它並不會檢查使用者的輸入是否超出字元陣列的長度,使用時必須小心,有的編譯器會提示警告訊息。
: the `gets' function is dangerous and should not be used.

对于代码:
1int main()
2{
3    char str[9];
4    puts("input a string:");
5    gets(str);
6    puts(str);
7    return 0;
8}

在VS 2005中,如果输入了一个长度大于8(9-1)的字符串,VS 2005在编译期不给出上述警告,但是在执行完毕后会跳出对话框提示:
Run-Time Check Failure #2 - Stack around the variable 'str' was corrupted.

posted on 2009-01-21 15:37 rdu 阅读(308) 评论(0)  编辑 收藏 引用 所属分类: 论坛拾珠


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理