仅以长列表的前五行为例(c++)
Take only the first five rows of a long list separated by empty lines (C++)
我有点卡在我想用我的c++代码做什么:
int main() {
char bid_price[512];
char bid_volume[512];
char ask_price[512];
char ask_volume[512];
const int MAX_LEN = 512;
ifstream in_stream;
in_stream.open("test.txt");
char current_string[MAX_LEN];
if (!in_stream) {
cout << "Could not open data.txt" << endl;
return false;
}
for (int i=0; i<150 &&
(in_stream.getline(current_string,MAX_LEN) && current_string.length()==0); i++) {
in_stream.getline(current_string, MAX_LEN);
get_word(current_string, 1, bid_price);
cout << "First word is: " << bid_price << endl;
get_word(current_string, 2, bid_volume);
cout << "Second word is: " << bid_volume << endl;
get_word(current_string, 4, ask_price);
cout << "Third word is: " << ask_price << endl;
get_word(current_string, 5, ask_volume);
cout << "Fourth word is: " << ask_volume << endl;
}
in_stream.close();
return 0;
}
我想做的是在一个txt文件中只取这样一个列表的前五行,如下所示:
- 383.80000 | 0.014 | 1461142717 | 383.67000 | 5.141 | 1461142798
- 383.61100 | 0.010 | 1461134871 | 383.60000 | 9.076 | 1461142798
- 383.51100 | 0.010 | 1461136836 || 383.46100 | 0.400 | 1461142794
- 383.41100 | 0.010 | 1461129820 | 383.35000 | 7.740 | 1461142798
- 383.31100 | 0.010 | 1461129821 || 383.30000 | 0.014 | 1461142637
- 383.21100 | 0.010 | 1461138430 || 383.20000 | 2.000 | 1461142787
- 383.16100 | 9.089 | 1461142763 || 383.11100 | 0.010 | 1461134135
- "空行"
- 383.01100 | 8.573 | 1461138900 || 383.00000 | 50.037 | 1461142501
- 382.98300 | 5.000 | 1461135929 || 382.97000 | 0.150 | 1461142461
- 382.93400 | 3.476 | 1461138822 || 382.91100 | 0.010 | 1461128348
- 382.81900 | 8.762 | 1461136840 || 382.81100 | 0.010 | 1461128350
- 382.80000 | 0.014 | 1461141922 || 382.71100 | 0.010 | 1461142621
- 382.68000 | 15.936 | 1461142797 || 382.67000 | 2.000 | 1461141655
- 382.66900 | 4.305 | 1461130920 || 382.61100 | 0.010 | 1461136076
在本例中,我只取行号1,2,3,4,5和9,10,11,12,13注意:别管get_word
函数,它工作得很好。
看起来您想要跳过空行。比担心要读多少行文本要容易得多:
std::string text_line;
while (getline(in, text_line))
{
// If text line is blank, skip it
if (text_line.empty())
{
continue;
}
// Otherwise process the text line.
// ...
}
我强烈建议您对不符合格式的行添加更多的错误检测。
编辑1:跳过特定行
要跳过特定的行,您需要有一个行计数器和一个要跳过的行容器。
const unsigned int lines_to_skip[] = {8, 24, 25, 26, 101, 113, 125};
const unsigned int skip_list_size = sizeof(lines_to_skip) / sizeof(lines_to_skip[0]);
std::string text_line;
unsigned int line_counter = 0;
unsigned int skip_index = 0;
//...
while (getline(in, text_line))
{
++line_counter;
if (skip_index < skip_list_size)
{
if (line_counter == lines_to_skip[skip_index])
{
++skip_index;
continue;
}
}
// Perform other validations
// ...
// Process the text line.
}
跳过空白和无效行比按行号跳过行要有效得多。
你想读5行,忽略空行。
所以,一个简单的方法是首先从你的数据集中删除所有空行,然后只抓取前5行。
另一种方法是跟踪成功读取了多少行,当该变量小于5时,再读取1行。然后,仅在读取非空白行时增加计数器,而在跳过空白行时不增加计数器。继续执行,直到计数器为5,或者没有行可读。
相关文章: