如何用c++打印从文本文件中提取的非英文字符

How can I print non English characters taken from a text file in c++?

本文关键字:文字符 字符 提取 打印 c++ 何用 文本 文件      更新时间:2023-10-16

我正在尝试编写一个简单的c++程序。


目标:打开一个现有的文本文件,获取名称和姓氏,并将其保存为名称和姓氏字符串。打印姓名并跳到下一行。重复直到文件结束。

我有两个问题

我使用的是windows 8.1和visual studio 2017的最新更新。

主要代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "stdafx.h"
#include <iostream>
using namespace std;

int main() {
FILE *fPtr;

if ((fPtr = fopen("newStudentsList.txt", "r")) == NULL) {
cout << "File could not be opened.n";
system("pause");
}

else {
char *name = new char[100];
char *surname = new char[100];
rewind(fPtr);
while (!feof(fPtr)) {
fscanf(fPtr, "%st%sn", name, surname);
cout << name << " " << surname << endl;
}
system("pause");
}
return 0;
}

在输出中,我无法正确地看到土耳其字符。这是我的第一个问题。


我的第二个问题是我不能正确地取名字和姓氏,因为在文本文件中,它们不是用相同的制表符或空格写的,有些人只有一个名字,有些人有两个名字。


所有文件都在这里


如何打印非英文字符?


如何正确取名字和姓氏?

首先,不要在C++程序中使用C函数。C++有不同的特性、不同的抽象和不同的库。使用C构造会阻止您使用它们。

C++使用流通过网络等读取/写入文件、内存和字符串缓冲区。它有大量算法,需要流和/或迭代器作为输入。

它还具有内置的字符串类型,可以处理单字节(std::string)、多字节(std::wstring)、UTF16(std:::u16string)和UTF32(std::u32string)库。您可以在代码中指定这样的字符串文字。它甚至有一种带有auto关键字的类型推理形式。

C++仍然没有UTF8的类型。程序员应该将UTF8字符串和文件视为单字节数据,并使用charstd::string来存储它们。这些值应根据需要转换为其他代码页或Unicode类型。

这意味着您不需要做更多的事情来向控制台显示UTF8文件的内容。代码取自文件输入/输出教程:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("newStudentsList.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << 'n';
}
myfile.close();
}
else cout << "Unable to open file"; 
return 0;
}

默认情况下,控制台使用系统区域设置的代码页。您可以通过键入:将其更改为UTF8代码页

chcp 65001

在运行应用程序之前。假设控制台字体包含正确的字符,则UTF8字符串应正确显示

更新

可以指定UTF8文字,但存储仍然是char,例如:

const char* str1 = u8"Hello World";  
const char* str2 = u8"U0001F607 is O:-)";  
const char*     s3 = u8"   = U0001F607 is O:-)"; 

auto str1 = u8"Hello World";  
auto str2 = u8"U0001F607 is O:-)";  

每当我需要在控制台程序中输出非ASCII字符时,我只需将控制台模式设置为支持UNICODE:

_setmode(_fileno(stdout), _O_U16TEXT);

一旦完成,宽字符感知代码将"按预期"工作,即此代码:

std::wcout << L"x046C" << std::endl;
wprintf(L"x046Cn");

将立即输出一个旧的西里尔字母"big-yus":Ѭ

请记住包括以下文件:

#include <io.h>
#include <fcntl.h>

这里有一个简短的测试程序供您使用:

#include <conio.h>
#include <iostream>
#include <io.h>
#include <fcntl.h>
void main(){
_setmode(_fileno(stdout), _O_U16TEXT);
std::wcout << L"x046C" << std::endl;
wprintf(L"x046Cn");
}