stream判断数组长度大于0,char数组的strlen大于其大小。如何避免?

I defined an array:

char arr[1480];

Now, from a file, I read exactly 1480 chars and put into arr (by doing arr[i]=c).

I know 1480 chars because I use a while loop to read one char ar a time (istream.get()) and stop when the incrementing index = 1480.

However, after that, I do strlen(array) and it returns 1512. How come? This only happens in some occasions, but not in all occasions, even though every time I read from file, I always read up to 1480 chars.

My doubt is one char might occupy more than 1 unit (units returned by strlen(arr)).

If so, how can I fix this?

Thanks

PS: I asked a problem earlier about my pointer gets garbaged, and this is the cause when I have a buffer (arr) of length > 1480.

解决方案

The array size must include the string terminator. Since you read exactly the size of the array then you can't (and don't) add the string terminator. The strlen function, and all other string functions, uses the string terminator character to find the end of the string. If it's not there it will continue until it finds it.

If you may have no more than 1480 characters in the string, you should have an array of size 1481, with the last being the string terminator '\0'.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值