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

有代码不理解,求大佬帮忙!

a75692074 发布于 2018-08-28 09:59, 2315 次点击
程序代码:

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main()
{
    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);
    cout << "You entered: " << charr << endl;
    cout << "Enter another line of text:\n";
    getline(cin, str);
    cout << "You entered: " << str << endl;
    cout << "Length of string in charr after input: "
         << strlen(charr) << endl;
    cout << "Length of string in str after input: "
         << str.size() << endl;
    return 0;
}


为什么这一段

   
cout << "Length of string in charr before input: "
     << strlen(charr) << endl;


结果是

Length of string in charr before input: 3


求大佬帮忙解释一下
4 回复
#2
rjsp2018-08-28 11:14
strlen 的参数要求  pointer to the null-terminated byte string to be examined
你的 charr 是一个以'\0'结尾的字符串吗?
好像还没赋值吧
#3
a756920742018-08-29 11:55
回复 2楼 rjsp
但它可以打印结果,是3,我不知道为什么
#4
花脸2018-08-29 17:13
strlen所作的仅仅是一个计数器的工作,它从内存的某个位置(可以是字符串开头,中间某个位置,甚至是某个不确定的内存区域)开始扫描,直到碰到第一个字符串结束符'\0'为止,然后返回计数器值(长度不包含“\0”)。
所以,可能是缓冲区中有字符串吧。
#5
汉家萌妹子2018-08-29 20:10
应该就是楼上说的这个问题
1