65.9K
CodeProject 正在变化。 阅读更多。
Home

在 MS VC++ 2005 中处理非英文字符 UTF8

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.22/5 (7投票s)

2008年11月6日

LGPL3

1分钟阅读

viewsIcon

19391

本文档描述了如何处理非英语字符流。

引言

作为 MS Visual Studio 的初学者,以及一名西班牙语使用者,我经常在处理非英语字符时遇到问题。 这篇简单而简短的文章描述了如何使用 UTF8 字符映射读取/写入文本文件,以及我在 Visual Studio 2005 中遇到的一些问题。

背景

在我的大学生活中,我所学的编程都面向于创建后台代码,而不是最终用户程序。 因此,我熟悉与 GCC 编译器相关的常见问题,并且一切都运行良好。 直到我需要制作一个最终用户应用程序。 这不是一个很大的障碍,但对很多人来说是一个障碍。 我想分享我是如何解决它的。

Using the Code

我首先尝试使用基本的 fstream 类,但在 VS 中,使用的 char 类型是 7 位 char,并且尝试将其与 wchar_t 一起使用时,没有显示任何重载函数错误。 因此,从那时起,我决定不得不使用著名的 CLR,而不知道这仅仅是我问题的开始。

我从 FileStream 类开始,但没有取得很大的成果。 使用的字符串是 7 位(再次)。 然后,最终,我找到了 StreamReadStreamWrite 类。 以下是一些使用此字符映射读取和写入文件的简单代码。

#include "stdafx.h"
#using <mscorlib.dll>

using namespace System;
using namespace System::IO;
using namespace System::Text;

int main(array<System::String ^> ^args)
{
    String^ filein;
    String^ fileout;
    Console::WriteLine(L"Enter file name: ");
    filein = Console::ReadLine();
    fileout = "out"+filein;

    StreamReader ^srp = gcnew StreamReader(filein, 
                        System::Text::Encoding::GetEncoding(1252));
    StreamWriter ^swp = gcnew StreamWriter(fileout, false, 
                        System::Text::Encoding::GetEncoding(1252));
    
    swp->WriteLine(L"Some simple header text with á é ä Ñe");
        
    String ^cont ;
    while (cont = srp->ReadLine())
    {
        swp->WriteLine(cont); 

       }
    swp->Close();
    srp->Close();
    delete(IDisposable^) swp;
    delete(IDisposable^) srp;

    return 0;
}

关注点

一个有趣的点是,在这个程序中生成的文本文件在 VS 文件编辑器中可以被很好地读取。 我使用上下文编辑器进行了检查。 我认为这可能是因为 VS 的默认语言设置。

© . All rights reserved.