[英]c++ how to read input up to a certain point
嗨,我按顺序输入了以下几行:
Date, Time, Price, Volume, Value,
日期采用DD / MM / YY格式,时间采用HH / MM / SS AM / PM格式,而价格,数量和价值是用逗号分隔的数字。
此输入有4000行,“ value”逗号后面有时会出现一个共享代码,例如“ CX”或“ NXXT”。
我的程序无法处理此问题并崩溃。
我需要的是一种忽略“值”后逗号以外的内容并继续阅读下一行的方法。 这将在“ Shares”类中。
以下是我班上的输入流:
类:“日期”
istream & operator >> (istream & input, Date & C) /// An input stream for the day, month and year
{
char delim;
input >> C.day >> delim >> C.month >> delim >> C.year;
return input; /// Returning the input value
}
上课时间'
istream & operator >> (istream & input, Time & C) /// An input stream for the hour minutes and seconds
{
char delim;
input >> C.hour >> delim >> C.minute >> delim >> C.second;
getline(input,C.ampm,',');
return input; /// Returning the input value
}
类别“股份”
istream & operator >> (istream & input, Shares & C) /// An input stream for the day, month and year
{
char delim;
input >> C.price >> delim >> C.volume >> delim >> C.value >> delim;
return input; /// Returning the input value
}
编写一个跳过直到行尾的函数。
void skipEOL(std::istream& in)
{
int c;
while ( (c = in.getc()) != '\n' && c != EOF );
}
当您知道需要跳过所有内容直到并包括该行的末尾时,请使用它。
看起来,共享是代表不同字段的数据结构。 编写一个函数,以更健壮的方式解析行。 理想情况下,如果“份额”代表一行的数据,则只需将其放在输入字符串的一行中即可。 即使存在其他行,该对象也不需要知道。
无论如何,不仅要编写这样的流函数,还远远不够鲁棒。 std :: getline将允许您在分隔符上分割行。 当然,即使使用“ std :: getline”,您仍然最好进行适当的验证。 并且您可以使用各种输入对其进行测试,例如,可以为Shares
提供一种从字段中重构线的方法,然后进行单元测试以将其与输入进行比较以验证其是否相同。
看一下torset中的此函数 ,该函数解析tor共识文件中的行,并仅提取ip地址和端口。 它将结果集存储在数据成员std::string _set;
,因为这里并不是将所有字段保留在数据结构中的目的。 请注意,此功能不会进行验证,因为它假定tor共识文件格式正确。 原则上,这是一个危险的假设,理想情况下,您永远不会在生产中运行此假设:
IpsetRestore::IpsetRestore( const std::stringstream& consensusIn, const std::string& setName )
: consensus ( consensusIn.str() )
, setName ( setName )
, _errorCode ( 0 )
{
std::string line ;
std::vector<std::string> fields ;
std::string field ;
std::stringstream lineStream;
// get each line separately
//
while( std::getline( consensus, line ) )
{
fields .clear();
lineStream.clear();
lineStream.str ( line );
// get each field
//
while( std::getline( lineStream, field, ' ' ) )
fields.push_back( std::string( field ) );
// only work on lines that interest us
// sample: "r Unnamed VLNV4cpI/C4jFPVQcWKBtO2EBV8 2013-11-04 22:38:31 76.100.70.54 9001 9030"
//
if( fields.size() != 8 || fields[ 0 ] != "r" )
continue;
// write add lines in the ipset format
// add [setName] [ip]:[port]
// tor uses tcp and ipset defaults to tcp, so we won't put it in
// fields 6 and 7 are the port fields, so if it's port 0, don't bother
//
for( int i = 6; i <= 7; ++i )
{
if( fields[ i ] == "0" )
continue;
_set.append
(
std::string( "add " )
.append ( setName )
.append ( " " )
.append ( fields[ 5 ] )
.append ( ":" )
.append ( fields[ i ] )
.append ( " -exist\n" )
);
}
if( _set.empty() )
{
std::cerr << "Something went wrong, _set is empty. Maybe you passed the wrong inputfile or it was not formatted correctly." << std::endl;
++_errorCode;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.