字符数组的长度限制 [英] Length limit of array of characters

查看:143
本文介绍了字符数组的长度限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与下面显示的程序有关(环境为Mac Xcode).

My question revolves around the program shown below (environment is Mac Xcode).

#include <iostream>
int main () {
    char nameOne [5];
    std::cin  >> nameOne; // input: BillyBobThorton
    std::cout << nameOne; // output: BillyBobThorton

    char nameTwo [5] = "BillyBobThorton"; // compile error, initializer string too long
    std::cout << nameTwo;
    return 0;
}

我有一个长度为5的char数组,因此我希望可以在此数组中存储的最大字符数为4(加上空终止char).当我尝试将字符串存储到nameTwo变量时,确实是这种情况.但是,当我使用字符数组作为变量来存储用户输入时,该数组的长度将被完全忽略,并且该数组似乎会扩展以容纳额外的字符.

I have a char array of length 5, so I would expect the maximum amount of characters I could store in this array to be 4 (plus the null terminating char). And this is indeed the case when I attempt to store a string to the nameTwo variable. However, when I use an array of characters as the variable to store user input, the array length is outright ignored and the array seemingly expands to accomodate the extra characters.

为什么会这样,也许有一种更合适的方法将用户输入存储到字符数组中?

Why is this the case, and is there perhaps a more appropriate way to store user input to an array of characters?

推荐答案

也许有更合适的方法将用户输入存储到字符数组中吗?

是的!在C ++中,最合适的方法是使用 std::string .这将防止您的用户超出分配的缓冲区的末尾并破坏堆栈.如果只想显示一定数量的字符,则可以使用 std::string::substr() .这是一个例子.

Is there perhaps a more appropriate way to store user input to an array of characters?

Yes! The most appropriate way in C++ is to use std::string. This will prevent your user overrunning the end of the buffer you've allocated and corrupting your stack. If you only want to display a certain number of characters, you can limit on output (or during some validation routine) using std::string::substr(). Here's an example.

#include <iostream>
#include <string>

int main ()
{
    std::string nameOne;
    std::cin >> nameOne; // input: BillyBobThorton
    std::cout << nameOne.substr(0, 5); // output: Billy

    const std::string nameTwo = "BillyBobThorton";
    std::cout << nameTwo.substr(0, 5); // output: Billy
    return 0;
}

这篇关于字符数组的长度限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆