【发布时间】:2014-05-24 10:25:36
【问题描述】:
我正在尝试将逗号分隔文件中的数据读入字符串。此外,我希望从字符串中删除多余的空格。
我已经设法实施了一个可行的解决方案,但我很感兴趣如果这可以更有效地完成。我的主要目标是删除具有默认字符串大小(std::string lName( 100, 0 );)的临时字符串初始化,因为文件中的数据是可变长度的。
另外,如果您有一些建设性的建议,我将不胜感激。
我正在使用 MS Visual Studio 2008。
这是 SSCCE 示例:
#include <iostream>
#include <algorithm>
#include <string>
#include <fstream>
// helper function for removing extra spaces
void removeSpace( std::string &str )
{
str.erase( std::remove( str.begin(), str.end(), ' ' ), str.end() );
}
int main()
{
//========== let us construct a test file =====================//
//===== format is Last Name, First Name, Gender, Color, Birth Date =======//
std::ofstream os;
os.open( "test.txt" );
// first row
os << " Smith ," << " John ," << " Male , "
<< " Green , " << " 6 / 7 / 1960 \n";
// second row
os << " Mortensen ," << " Mike ," << " Male , "
<< " Red , " << "5/5/ 1975 \n";
// third row
os << " Johnson ," << " Ann ," << " Female , "
<< " Blue , " << " 4/ 4 /1985 \n";
os.close();
// now let us read data from it
std::ifstream g;
g.open( "test.txt" );
if( g.is_open() )
{
while( !g.eof() )
{
// temporary strings
std::string lName( 100, 0 );
std::string fName( 100, 0 );
std::string gen( 100, 0 );
std::string clr( 100, 0 );
std::string date( 100, 0 );
// get data from file
g.getline( &lName[0], 100, ',' );
g.getline( &fName[0], 100, ',' );
g.getline( &gen[0], 100, ',' );
g.getline( &clr[0], 100, ',' );
g.getline( &date[0], 100 );
// remove extra spaces from strings
removeSpace( lName );
removeSpace( fName );
removeSpace( gen );
removeSpace( clr );
removeSpace( date );
// display the result
std::cout << lName.c_str()
<< ' ' << fName.c_str()
<< ' ' << gen.c_str()
<< ' ' << clr.c_str()
<< ' ' << date.c_str()
<< std::endl;
//cleanup
lName.clear();
fName.clear();
gen.clear();
clr.clear();
date.clear();
}
g.close();
}
// since our SSCCE example is done, let us delete the test file
if( 0 != std::remove( "test.txt" ) )
std::cout << "Couldn't delete test file!\n\n";
else
std::cout << "Successfully deleted test file!\n\n";
return 0;
}
编辑:
根据成员 WhozCraig 的建议,我能够做出改进。为简洁起见,我将只发布while 循环:
while( !g.eof() )
{
// temporary strings
std::string line;
if( ! std::getline( g, line ) )
break;
std::istringstream iss(line);
while( iss )
{
std::string str;
if ( ! std::getline( iss, str, ',' ) )
break;
// remove excess spaces
removeSpace( str );
// output the result
std:: cout << str.c_str() << ' ';
}
std::cout << std::endl;
}
【问题讨论】:
-
SSCCE不需要编写文本文件,你可以简单地列出文本文件,不是吗?
-
@flup:那些解决方案主要使用Boost库,但我不能使用它。
-
std::getline的可选分隔符对此很有用,尤其是通过从同一函数读取的完整行填充的字符串流。但是在你的循环中丢失.eof()检查for these reasons。 -
@WhozCraig:英语不是我的母语,您能详细说明一下您的评论吗?到目前为止,我还没有机会使用字符串流,这也增加了我无法理解评论的能力。