C++核心准则​SL.io.1:只在必须的时候使用字符级别的输入

2020-10-30 11:33:50 浏览数 (1)

SL.io.1: Use character-level input only when you have to

SL.io.1:只在必须的时候使用字符级别的输入

Reason(原因)

Unless you genuinely just deal with individual characters, using character-level input leads to the user code performing potentially error-prone and potentially inefficient composition of tokens out of characters.

除非你就是需要处理单独的字符,除非您真的只处理单个字符,否则使用字符级别输入有可能导致用户代码执行容易出错,并导致字符中标记的处理效率低下。

Example(示例)

代码语言:javascript复制
char c;
char buf[128];
int i = 0;
while (cin.get(c) && !isspace(c) && i < 128)
    buf[i  ] = c;
if (i == 128) {
    // ... handle too long string ....
}

Better (much simpler and probably faster):

好一些(更简单而且可能更高效)

代码语言:javascript复制
string s;
s.reserve(128);
cin >> s;

and the reserve(128) is probably not worthwhile.

同时,reserve(120)可能并不值得。

Enforcement(实施建议)

???

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slio1-use-character-level-input-only-when-you-have-to

0 人点赞