我对要使用我的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.
}


跳过空白行和无效行比按行号跳过行要有效得多。

09-06 14:33