【问题标题】:How do I write arrow symbol to a file and then read it back?如何将箭头符号写入文件然后读回?
【发布时间】:2014-04-09 11:41:12
【问题描述】:

参考 http://www.fileformat.info/info/unicode/char/2192/index.htm 表示右箭头在 unicode 字符集中是 0x2192,所以我尝试以几种不同的方式将值写入文件:

#include <fstream>

using namespace std;

int main()
{
    ofstream out("out.txt");
    wofstream wout("wout.txt");

    out << '0x2192' << endl;
    out << '\u2192' << endl;
    out << L'\u2192' << endl;
    out << u'\u2192' << endl;

    wout << '0x2192' << endl;
    wout << '\u2192' << endl;
    wout << L'\u2192' << endl;
    wout << u'\u2192' << endl;

    return 0;
}

它只打印出数字,没有箭头符号。我究竟做错了什么? PS 另外我想稍后再读回这个角色。提前致谢。

【问题讨论】:

  • 字符“U+2192”在任何 Unicode 编码中都大于一个字节。 out 的所有行都不应该工作,但 out &lt;&lt; "\u2192"; 应该工作。 wout &lt;&lt; L'\u2192'; 也应该可以。请参阅 herehere。话虽如此,C++ 对于开箱即用的 Unicode 并不太强大。这是非常非常积极的。

标签: c++ unicode fstream


【解决方案1】:

经过一些修改:

#include <fstream>
#include <locale>

using namespace std;

int main() {
    // This is the real trick, make the wfostream to print wide characters as
    // UTF-8
    // what we're going to do is to create a locale that has the ctype category
    // copied from the "en_US.UTF-8"
    std::locale loc=std::locale(std::locale(),"en_US.UTF8",std::locale::ctype);
    ofstream out("out.txt");
    // and now add the locale to the stream
    out.imbue(loc);
    wofstream wout("wout.txt");
    // and now add the locale to the stream
    wout.imbue(loc);

    //out << '0x2192' << endl;           // character constant too long (did not compile on g++)
    //out << '\u2192' << endl;           // character constant too long (did not compile on g++)
    out << L'\u2192' << endl;            // prints 8594
    out << u'\u2192' << endl;            // prints 8594
    out << (wchar_t) L'\u2192' << endl;  // prints 8594
    out << (wchar_t) u'\u2192' << endl;  // prints 8594

    //wout << '0x2192' << endl;          // character constant too long
    //wout << '\u2192' << endl;          // character constant too long
    wout << 8594 << endl;                // prints 8594
    wout << L'\u2192' << endl;           // prints ->
    wout << u'\u2192' << endl;           // prints 8594
    wout << (wchar_t) 8594 << endl;      // prints ->
    wout << (wchar_t) L'\u2192' << endl; // prints ->
    wout << (wchar_t) u'\u2192' << endl; // prints ->    
    return 0;
}

以上是在 Ubuntu linux 上执行并用 g++ 编译的

【讨论】:

  • 谢谢!你帮了我很多!特别感谢所有 cmets!
猜你喜欢
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-26
  • 1970-01-01
  • 2012-05-15
  • 2021-12-06
相关资源
最近更新 更多