为什么我的字符串长度与我选择的不同?

Alc*_*isz 0 c++

我想用数字创建一个字符串。所以我将字符串数组的长度定义为 10,但是当我在控制台中启动程序时是 11 个字符。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define N 10

using namespace std;

int main()
{
    srand(time(0));
    int numArr[N];

    for(int i = 0; i < N; i++)
        numArr[i] = rand() % 26 + 97;

    for(int i = 0; i < N; i++)
        std::cout << numArr[i] << " ";
    std::cout << std::endl;

    char str[N] = "";

    for(int i = 0; i < N; i++)
        str[i] = numArr[i];

    std::cout << str << endl;
    std::cout << strlen(str);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Gau*_*man 5

一个字符串需要以 with 结尾\0以获得它的长度strlen,在代码str中没有以 结尾\0,当你添加它作为最后一个字符strlen给出正确答案时

#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define N 10

using namespace std;

int main()
{
    srand(time(0));
    int numArr[N];

    for(int i = 0; i < N; i++)
        numArr[i] = rand() % 26 + 97;

    for(int i = 0; i < N; i++)
        std::cout << numArr[i] << " ";
    std::cout << std::endl;

    char str[N + 1] = "";

    for(int i = 0; i < N; i++)
        str[i] = numArr[i];

    str[N] = '\0'; // terminate with \0

    std::cout << str << endl;
    std::cout << strlen(str);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)