【发布时间】:2016-12-21 14:50:31
【问题描述】:
我有一个 UTF-8 文本文件,其中包含几个我想被其他人更改的标志(仅限于 |( 和 |) 之间的那些),但问题是有些这些符号中的一些不被视为字符,而是被视为多字符符号。 (我的意思是它们不能放在“∞”之间,而只能放在“∞”之间,所以 char * ?)
这是我的文本文件:
Text : |(abc∞∪v=|)
例如:
∞ 应改为 ¤c
∪ by ¸!
= 更改为 "
因此,由于某些符号(∞ 和 ∪)是多字符,我决定使用 fscanf 逐字获取所有文本。这种方法的问题是我必须在每个字符之间放置空格......我的文件应该如下所示:
Text : |( a b c ∞ ∪ v = |)
fgetc 不能使用,因为 ∞ 之类的字符不能被视为单个字符。如果我使用它,我将无法使用每个符号(char *)strcmp 一个字符,我试图转换我的char 到 char* 但 strcmp !=0。
这是我的 C 代码,可帮助您理解我的问题:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void){
char *carac[]={"∞","=","∪"}; //array with our signs
FILE *flot,*flot3;
flot=fopen("fichierdeTest2.txt","r"); // input text file
flot3=fopen("resultat.txt","w"); //output file
int i=0,j=0;
char a[1024]; //array that will contain each read word.
while(!feof(flot))
{
fscanf(flot,"%s",&a[i]);
if (strstr(&a[i], "|(") != NULL){ // if the word read contains |( then j=1
j=1;
fprintf(flot3,"|(");
}
if (strcmp(&a[i], "|)") == 0)
j=0;
if(j==1) { //it means we are between |( and |) so the conversion can begin
if (strcmp(carac[0], &a[i]) == 0) { fprintf(flot3, "¤c"); }
else if (strcmp(carac[1], &a[i]) == 0) { fprintf(flot3,"\"" ); }
else if (strcmp(carac[2], &a[i]) == 0) { fprintf(flot3, " ¸!"); }
else fprintf(flot3,"%s",&a[i]); // when it's a letter, number or sign that doesn't need to be converted
}
else { // when we are not between |( and |) just copy the word to the output file with a space after it
fprintf(flot3, "%s", &a[i]);
fprintf(flot3, " ");
}
i++;
}
}
非常感谢您以后的帮助!
编辑:如果我在每个符号之间放置一个空格,每个符号都会正确更改,但如果没有,它将不起作用,这就是我要解决的问题。
【问题讨论】:
-
fgetwc()呢? -
很好的问题格式,但有一些小问题:避免使用
feof(stackoverflow.com/questions/5431941/…),将j改成不同的东西,比如is_converting或者因为j通常是一个迭代器。跨度> -
看看使用
fread()而不是fscanf()。由于您将 UTF-8 与多字节字符一起使用,您将需要一种机制来读取字节流,然后一次处理一个字符并识别 UTF-8 流中的多字节字符。另请参阅UTF8 processing C,另请参阅此博客帖子Using UTF-8 as the internal representation for strings in C and C++ with Visual Studio。 -
C: Using scanf and wchar_t to read and print UTF-8 strings 有一个简短的演示程序,演示了
setlocale(LC_ALL, "");以及%ls格式说明符的用法,如scanf("%ls",string);。