如何检查string :: append()是否会失败 [英] How do I check if string::append() is going to fail

查看:151
本文介绍了如何检查string :: append()是否会失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个代码,我需要通过向其附加数据来创建一个std :: string(这里的数据表示应用程序的日志)。但是字符串也有其大小限制。我已经在try-catch块中编写了代码,当append()失败时,它会抛出异常。我需要在append()之前检查是否附加新字符串会导致任何异常,因为一旦抛出异常,它就会清除字符串中的数据。

我想检查附加新字符串是否会导致任何异常如果是,则将数据写入文件并清除字符串以进行下一次输入。

由于它是应用程序日志,我不知道最终大小是多少。所以我试图使代码不易受到上述问题的影响。

我检查了一个条件如下:

如果current_string_size + to_be_attached_string_size超过string.max_size()然后将代码写入文件。

如果不,则将to_be_attached_string附加到current_string。

但它在某处失败。

我的条件是什么需要检查?

解决方案

引用:

如果current_string_size + to_be_attached_string_size超过字符串.max_size()然后将代码写入文件。

如果不,则将to_be_attached_string附加到current_string。

但它在某处失败。



那么,你得到一个 bad_alloc 异常吗?

我想知道为什么你不经常把字符串写入文件。


I am writing a code in which I need to create a std::string by appending data to it(here data means logs of an application). But string also has its limitation of size. I have written the code in try-catch block and when append() fails, it throws exception. I need to check before append() whether attaching new string will cause any exception, since once exception is thrown, it clears the data from string.
I want to check if attaching new string will cause any exception and if yes then write the data to a file and clear the string for next input.
As it is an application log, I do not know what the final size will be. So I am trying to make code less vulnerable to above explained problem.
I have checked one condition as follows:
If "current_string_size + to_be_attached_string_size exceeds string.max_size()" then write the code into file.
If "not" then append to_be_attached_string to current_string.
But it is failing somewhere.
What condition I need to check?

解决方案

Quote:

If "current_string_size + to_be_attached_string_size exceeds string.max_size()" then write the code into file.
If "not" then append to_be_attached_string to current_string.
But it is failing somewhere.


So, are you getting a bad_alloc exception?
I wonder why you don't write the string more frequently to the file.


这篇关于如何检查string :: append()是否会失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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