c++怎么读取文件中的中文字符串

我要写一个程序是从一个txt文件中读取中文然后存入excel表中,txt文件中每一行的文字存入excel一个格子中,我用fstream类调用getline函数之后读取一行之后存入一个char字符串,但是只能读取英文的,中文的读取不了,各位知道应该怎么办?
代码段:
fstream fin;
fin.open("config.txt",ios:base in);
char str[50];
while(!fin.eof() && fin.getline(str,50))
{....}

#include <fstream>
#include <string>
#include <iostream>
using namespace std;

int main()
{
ifstream ifs("test.cpp"); // 改成你要打开的文件
streambuf* old_buffer = cin.rdbuf(ifs.rdbuf());

string read;
while(cin >> read) // 逐词读取方法一
cout << read;
cin.rdbuf(old_buffer); // 修复buffer
}

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream ifs("test.cpp"); // 改成你要打开的文件
ifs.unsetf(ios_base::skipws);

char c;
while(ifs.get(c)) // 逐词读取方法二
{
if(c == ' ')
continue;
else
cout.put(c);
}
}

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
ifstream ifs("test.cpp"); // 改成你要打开的文件

string read;
while(getline(ifs, read, ' ')) // 逐词读取方法三
{
cout << read << endl;
}
}

#include <fstream>
#include <iostream>
using namespace std;

int main()
{
ifstream ifs("test.cpp"); // 改成你要打开的文件

char buffer[256];
while(ifs.getline(buffer, 256, ' ')) // 逐词读取方法四
{
cout << buffer;
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-01-20
可以用string来读取中文
#include"fstream"
#include"string"
using namespace std;
int main()
{
string s;
ifstream fin;
ofstream fout;
fin.open("F:\\1.txt");
fout.open("F:\\1.xls");
while(!fin.eof())
{
getline(fin,s); //读取一行字符,要求一行字符中没有制表符'\t',否则用本程序实现不了把一行字符输出到一格excle中
fout<<s<<'\n'; //输出字符,如果不想换行,就去掉'\n'
}
fin.close();
fout.close();
system("pause");
return 0;
}
第2个回答  2011-01-20
{
FILE *fp;
char buf[1000];
fp=fopen("student.txt","r");
if(!fp)
{
printf("打开文件出错\n");
return;
}

while(fscanf(fp,"%s",buf))>0)
{
..................................
}
fclose(fp);

}

这样就能每次读取一行字符串
第3个回答  2011-01-20
试试将txt文件另存为unicode编码。。。
第4个回答  推荐于2017-10-11
vs2008 、vs2005下 std::ifstream中不支持中文,是因为在vs2008 、vs2005 下,默认传入的 unicode 字符集 ,而一般开发的时候 大多数使用的多字节字符集,所以会导致出错 。
1、使用C语言的函数设置为中文运行环境
setlocale(LC_ALL, "Chinese-simplified");
2、使用STL函数设置为系统语言环境
std::locale::global(std::locale(""));
3. 或者 直接 修改 log4cpp 的 参数,直接传入的是 宽字节 。

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网