hi guys i am trying to work on the file and array at the same time. first i am trying to open the file and count how many numbers of contents are there in the file and again open the same file and output the contents in the file. but my program showing me a junk value. here i am going to paste my program. Thanks in advance.
You have an off by one error in your program. You are setting size to 1 more than the count of numbers available in the file. Change the above code to the following:
I tested with a sample file with my suggested changes and it works. Please note you are outputting numbers with no spaces between them. Therefore, all the numbers will be clubbed together & will appear as one long string. Is this the case? If not, please share us your input file and the output you get for us to figure out what is going on.
I am not quite sure I understand your response. The fix that I suggested on my first post was the only fix I made to your code to get the above result. I am re-posting that code here for your reference.
#include <iostream>
#include <fstream>
#include <vector>
int main()
{
std::vector<int> vec;
ifstream ifs("bignum.dat");
int n;
while(ifs >> n) vec.push_back(n);
for(unsignedint i = 0; i < vec.size(); ++i) std::cout << vec[i];
return 0;
}
Notice you don't need to call open() and close() for the ifstream because the constructor will take the file name and open it for you, while the destructor will close it for you. Also, avoid looping on eof() because there are other states the stream might go into (bad() and fail()) which you're not checking.