【问题标题】:Porting Perl to C++ `print "\x{2501}" x 12;` [duplicate]将 Perl 移植到 C++ `print "\x{2501}" x 12;` [重复]
【发布时间】:2013-11-09 17:49:17
【问题描述】:

我将一个程序从 Perl 移植到 C++ 作为学习目标。我遇到了一个用如下命令绘制表格的例程:

Perl: print "\x{2501}" x 12;

它会绘制 12 次 '━'(“方框图重水平”)。

现在我已经发现了部分问题:

Perl: \x{}, \x00        Hexadecimal escape sequence;
C++:  \unnnn

要打印单个 Unicode 字符:

C++:  printf( "\u250f\n" );

但是 C++ 是否有一个智能等效的 'x' 运算符或者它会归结为一个 for 循环?


更新 让我包含我尝试使用建议的解决方案编译的完整源代码。编译器确实会抛出错误:

g++ -Wall -Werror project.cpp -o project
project.cpp: In function ‘int main(int, char**)’:
project.cpp:38:3: error: ‘string’ is not a member of ‘std’
project.cpp:38:15: error: expected ‘;’ before ‘s’
project.cpp:39:3: error: ‘cout’ is not a member of ‘std’
project.cpp:39:16: error: ‘s’ was not declared in this scope


#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <iostream>

int main ( int argc, char *argv[] )
{
        if ( argc != 2 )   
        {
                fprintf( stderr , "usage: %s matrix\n", argv[0] );
                exit( 2 );
        } else {
                //std::string s(12, "\u250f" );
                std::string s(12, "u" );
                std::cout << s;
        }       
}

【问题讨论】:

标签: c++ perl


【解决方案1】:

不,C++ 没有“x”运算符,但是您可以创建一个字符重复的字符串:

std::string s(12, <any character>);

然后你可以像下面这样打印它(“printf”是从C继承的,在你的作业中使用它可能不好):

std::cout << s;

(当然,你可以使用任何数字,而不仅仅是 12)

UPDATE为您的上述更新:

我可以编译您的代码,只需稍作改动(“u”替换为“u”,因为它必须是一个字符)。我的编译器是 GCC 4.6.2 for Windows XP(MINGW32 版本)。你使用什么操作系统/编译器?

【讨论】:

  • 或者,更直接地说,std::cout &lt;&lt; std::string(12, '\u250f');
  • @LightnessRacesinOrbit 我猜我也得去谷歌搜索 cout 和 printf。
  • @jippie:不,不要谷歌它。阅读a recommended book
  • @jippie #include &lt;string&gt;
  • std::wstring? std::wcout?
猜你喜欢
  • 2013-01-29
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
  • 2017-07-04
  • 1970-01-01
  • 1970-01-01
  • 2012-05-12
  • 1970-01-01
相关资源
最近更新 更多