与C的格式字符串等效的C ++ [英] The C++ equivalent of C's format string

查看:87
本文介绍了与C的格式字符串等效的C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从键盘读取的C程序,如下所示:

I have a C program that reads from keyboard, like this:

scanf("%*[ \t\n]\"%[^A-Za-z]%[^\"]\"", ps1, ps2);

为更好地理解此指令的作用,让我们按如下方式分割格式字符串:

For a better understanding of what this instruction does, let's split the format string as follows:

%* [\t\n] \ =>读取所有空格,制表符和换行符( [\t\n] ),但不将其存储在任何变量中(因此,' * '),并且将一直读取直到遇到双引号( \ ),但不会输入双引号。

%*[ \t\n]\" => read all spaces, tabs and newlines ([ \t\n]) but not store them in any variable (hence the '*'), and will keep reading until encounter a double quote (\"), however the double quote is not input.

一旦找到 scanf()双引号将所有不是字母的角色读入ps1中。这是通过...

Once scanf() has found the double quote, reads all caracters that are not letters into ps1. This is accomplished with...

%[^ A-Za-z ] =>输入除大写字母 A至 Z以及小写字母 a至 z之外的任何内容。

%[^A-Za-z] => input anything not an uppercase letter 'A' through 'Z' and lowercase letter 'a' through 'z'.

%[^ \] \ =>读取所有剩余字符,但不包括ps2中的双引号( [^ \ ] )和字符串必须以双引号( \ )结尾,但是不输入双引号。

%[^\"]\" => read all remaining characters up to, but not including a double quote into ps2 ([^\"]) and the string must end with a double quote (\"), however the double quote is not input.

有人可以教我如何在C ++中做同样的事情

Can someone show me how to do the same thing in C++

谢谢

推荐答案

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()将失败,并且如果在<$ c $之前不存在任何空格字符,则返回 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()

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>.

这篇关于与C的格式字符串等效的C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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