读取以空格分隔的字符串

朋友让我帮忙写一个程序,从一个文件中读取以空格分隔的字符串数据.这看起来似乎是一件很简单的事情,但是我实际写的时候却遇到了不少麻烦例如,如果是在win下,locale必须设置为"chinese-simplified"而不是"zh_CN.GB2312"

#include <iostream>
#include <fstream>
#include <iterator>
#include <locale>
#include <string>
#include <vector>

///每个字符串的最大长度,包括'\0'
#define MAX_LENTH_PER_STRING 1024

///文件的locale
#define STREAM_LOCALE "chinese-simplified"

template <typename T>
std::vector<std::basic_string<T> > readData(std::basic_istream<T>& is);

int main(int argc,char* argv[]){
std::wifstream fs("C:\\test.txt"); 
std::vector<std::wstring> datastrings;
try{
fs.imbue(std::locale(STREAM_LOCALE));
datastrings=readData<wchar_t>(fs); 
}
catch (const std::ios::failure& error) {
std::cerr << "I/O exception: " << error.what() << std::endl;
fs.close();
return EXIT_FAILURE;
}
catch (const std::exception& error) { 
std::cerr << "standard exception: " << error.what() << std::endl;
fs.close();
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "unknown exception" << std::endl; 
fs.close();
return EXIT_FAILURE;
}

fs.close();

std::wcout.imbue(std::locale(STREAM_LOCALE)); //坚决不能少,否则后面输出汉字的时候就会扔出std::ios::failure错误
std::wcout.exceptions (std::ios::failbit | std::ios::badbit);
try{
std::copy(datastrings.begin(),datastrings.end(),std::ostream_iterator<std::wstring,wchar_t>(std::wcout,L" ")); 
}
catch (const std::ios::failure& error) {
if(!std::wcout.eof()){
std::cerr << "I/O exception: " << error.what() << std::endl;
return EXIT_FAILURE;
}
}
catch (const std::exception& error) {
std::cerr << "standard exception: " << error.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "unknown exception" << std::endl; 
return EXIT_FAILURE;
}

return 0;
}

template <typename T>
std::vector<std::basic_string<T> > readData(std::basic_istream<T>& is){
std::vector<std::wstring> datastrings;
std::ios::iostate oldExceptions = is.exceptions ();
is.exceptions (std::ios::failbit | std::ios::badbit);
try{
while(!is.eof()){
wchar_t data[MAX_LENTH_PER_STRING];
is.getline(data, MAX_LENTH_PER_STRING, L' ' ); 
datastrings.push_back(data); 
}
}
catch (...) {
/*if exception not caused by end-of-file
*- restore old state of exception flags
*- rethrow exception
*/
if (!is.eof()) {
is.exceptions (oldExceptions); // restore 
throw; // rethrow
}
}
is.exceptions (oldExceptions);
return datastrings;
}

此博客中的热门博文

少写代码,多读别人写的代码

在windows下使用llvm+clang

tensorflow distributed runtime初窥