I am trying to read from a file in an integer and doing some operations and output them to another file I am here. When I input integers into an array and then print the result of coming with random numbers. Is it from such streams that I do not understand or am I not clarifying anything?
# include & lt; Iostream & gt; #to & lt include, fstream & gt; using namespace std; Int main () {int i = 0, test [100]; Ifstream Reader ("in.txt"); While (! Reader.eof ()) {Reader & gt; & Gt; Test [i]; I ++; } For (int x = 0; test [x]! = - 1; x ++) cout & lt; & Lt; Test [x] & lt; & Lt; Endl; Return 0; }
in.txt sample:
1 4 3 2 9 8 18 22 0 2 4 8 10 0 7 5 11 13 1 3 -1
0 and -1 are respectively sent to eol and eof
If this is a very easy way to do this, then I should also know that I rather +++++++++++++++++++++++++++++++++++++++
sizeof (test) / size (test [0])
This is a compilation time calculation: it will always keep the result in 100. If you want to know exactly how many integers you read, then you need to keep an eye on it (or like std :: vector
, use a container to keep track of it for you. )
In addition, the test is eof ()
in the loop position and the loop will not end at the right time. If extraction fails, then the failed state will be set on the stream and further withdrawal will fail. The correct way to do this is:
// Be sure to check the Aure and check that the extraction was successful: while ((i & lt; 100) & amp; amp; amp ; Amp; amp; amp; (& amp; Reader & gt; & # 39; Exam [i])) {i ++; }
Then you can test the status of the stream to determine whether the loop has expired due to the extraction failure or because the eof was reached. If there was no case, then i
should be 100 and you will fill the array.
You can tell why it is the right way to do this.
Comments
Post a Comment