0

I have a file which I have opened using:

ifstream ifile(FilePath)

The file contains, say 10 lines of data and each line contains an evenly-incrementing number of comma separated values (like a pyramid). So first line has 1 value, second line has 2 values and so on....

I wanted to do the following, all within one function (whilst traversing the file char array just the once):

-Every time I encounter a newline character, I can increment a parameter passed in by value (which, when the function exits, I have the number of lines in the file).

-I also wanted to store each line of the file in an array. What would be the best way to "glue" together all the characters between newline characters?

I'd prefer to use statically-allocated arrays, but the problem is I only know the size of the array once I have performed step 1 (counting how many new line characters there are). Would it be quicker to perform a double-parse for this (one parse to count how many lines, then use that value to allocate a static array) or single parse, but insert into a dynamic array?

The emphasis on this is to write fast code (so not being OO-friendly is not a concern)

Apologies if I am asking a lot, hopefully you can see I have given this some thought.

EDIT, example file:

a

b,c

d,e,f,g,h

j,k,l,m,n,o,p

From this file I would want to achieve:

  • Knowledge that there are 4 lines in the file
  • A non-dynamic array containing each line
  • The number of elements in the second line
4

1 回答 1

0

现有帖子中有很多关于如何执行此操作的示例。

如果您想使用 ifstream 读取文件一次,您可以执行以下操作:

std::ifstream in("myfile");

std::stringstream buffer;
buffer << in.rdbuf();

std::string contents(buffer.str());
于 2012-12-13T20:51:22.907 回答