且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

与C的格式字符串等效的C ++

更新时间:2023-02-06 18:10:58

C ++支持 scanf 函数。没有简单的选择,尤其是如果您要使用所有怪癖来复制 scanf()的确切语义。

C++ supports the scanf function. There is no simple alternative, especially if you want to replicate the exact semantics of scanf() with all the quirks.

但是请注意,您的代码有几个问题:

Note however that your code has several issues:


  • 您没有将最大字符数传递给 ps1 ps2 。任何足够的输入序列都会导致缓冲区溢出,并带来严重后果。

  • You do not pass the maximum number of characters to read into ps1 and ps2. Any sufficiently input sequence will cause a buffer overflow with dire consequences.

您可以简化第一种格式%* [\t\ \n] ,格式字符串中只有一个空格。这也将允许不存在空格字符的情况。如当前所写, scanf()将失败,并且如果在 0 。 c> 。

You could simplify the first format %*[ \t\n] with just a space in the format string. This would also allow for the case where no whitespace characters are present. As currently written, scanf() would fail and return 0 if no whitspace characters are present before the ".

类似地,如果在第二个之前没有非字母或没有其他字符 scanf 会返回简短的 0 1 并将一个或两个目标数组保留为不确定状态。

Similarly, if no non letters or if no other characters follow before the second ", scanf would return a short count of 0 or 1 and leave one or both destination array in an indeterminate state.

对于所有这些原因,在C语言中,首先使用 fgets()读取一行输入并使用 sscanf()$ c会更安全和可预测

For all these reasons, it would be much safer and predictable in C to first read a line of input with fgets() and use sscanf() or parse the line by hand.

在C ++中,您肯定要使用 std :: regex ® regex.h> 中定义的软件包。

In C++, you definitely want to use the std::regex package defined in <regex.h>.