如何用c++打印从文本文件中提取的非英文字符
How can I print non English characters taken from a text file in c++?
我正在尝试编写一个简单的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字符串和文件视为单字节数据,并使用char
和std::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");
}
- const_cast<字符 *>(字符* 常量) 不是左值?
- 如何将字符*(字符指针)转换为 PCSZ?
- 回文,不包括特殊字符和空格
- 将 C++ std::string 中的字符/字符序列替换为另一个字符序列
- 声明多字符字符的警告和错误
- 你如何打印出使用数组删除某些字符的回文
- 如何获取字符*(字符数组)的真实长度和总长度
- 我得到以下错误:[警告]多字符字符常量
- C++错误:警告:多字符字符常量/a用于用法
- 用于识别回文字符数组的递归函数
- Char Val = 'ABCD'。使用多字符字符
- 警告多字符字符常量 [-Wmultichar]
- 如何截断前几个字符字符数组 C++
- 手动计算回文的字符数
- 比较C++字符* 字符进行解析.OBJ 文件
- 如何将字符串标记复制到字符 */字符数组
- C++与n-Gram的最快文本行比较?使用字符串、字符*、矢量
- c++ cin.ignore忽略空格、数字和字符来测试回文
- 回文查找器:非字母数字字符删除问题
- 回文程序和 C 样式字符串中不需要的字符