注册 登录
编程论坛 C++教室

20位的数组,为什么输出是27(31)呢?

lxfeng1988 发布于 2014-01-01 11:53, 459 次点击
程序清单:
//strtype4.cpp--line input
#include<iostream>
#include<string>  //make string class available
#include<cstring>  //C-style string library
int main()
{
    using namespace std;
    char charr[20];
    string str;
    cout<<"Length of string in charr before input: "
        <<strlen(charr)<<endl;
    cout<<"Length of string in str before input: "
        <<str.size()<<endl;
    cout<<"Enter a line of text:\n";
    cin.getline(charr,20);  //indicate maximum length
    cout<<"You entered: "<<charr<<endl;
    cout<<"Enter another line of text:\n";
    getline(cin,str);  //cin now an argument;no length specifier
    cout<<"Length of string in charr after input: "
        <<strlen(charr)<<endl;
    cout<<"Length of string in str after input: "
        <<str.size()<<endl;
    return 0;
}
请问输出结果“Length of string in charr before input”是什么(我觉得应该是20)呢?
书上给出的结果是27
而我敲进编译器给出的结果是31
求大神指导!!!
3 回复
#2
yuccn2014-01-02 08:14
cout<<"Length of string in charr before input: "
        <<strlen(charr)<<endl;  
你的charr 是没有初始化的,计算strlen 当然是错误的了

书上应该不是这样写吧
#3
lxfeng19882014-01-03 08:57
回复 2楼 yuccn
明白了,谢谢。
#4
华子hear2014-01-04 12:46
Length of string in charr before input: 3
Length of string in str before input: 0
Enter a line of text:




为什么我的是3呢  初始化要怎么弄 一旦初始化不是就成0了嘛?
1