You are writing the numbers to the file without any delimiters between them, so the file will contain one long digit sequence in it, ie 012345678910
. You won't be able to make sense of that, no matter how you read it. So, separate the numbers to make them easier to read.
More importantly, after writing to the file and seeking (the output position) to the beginning (rather than seeking the input position), you are then calling getline()
to read the entire file into a std::string
, and then you are trying to convert that entire string
into an int
, but the value 012345678910
exceeds the max value that int
can hold (2147483647
), so stoi()
will fail.
You can try this instead:
fstream myFile;
myFile.open("numbers.txt", ios::in | ios::out);
int sum = 0;
if (myFile.is_open()) {
for (int i = 0; i <= 10; i++) {
myFile << i << ' ';
}
myFile.seekg(0, ios::beg);
int number;
while (myFile >> number) {
sum += number;
}
}
cout << "Sum: " << sum << endl;
Online Demo
However, note that when you are opening the file, you are specifying both the in
and out
flags. That will fail if the file does not already exist (even if it is blank). So, if you need to create a new file, the in
flag must not be specified, but then you can't read from the file, only write to it. See this documentation for std::basic_filebuf::open()
to understand why.
So, you would have to open the file for writing, then close and reopen it for reading, eg:
fstream myFile;
myFile.open("numbers.txt", ios::out);
if (myFile.is_open()) {
for (int i = 0; i <= 10; i++) {
myFile << i << ' ';
}
myFile.close();
}
int sum = 0;
myFile.open("numbers.txt", ios::in);
if (myFile.is_open()) {
int number;
while (myFile >> number) {
sum += number;
}
myFile.close();
}
cout << "Sum: " << sum << endl;
Online Demo
In which case, you should use ifstream
and ofstream
separately, instead of using fstream
, eg:
ofstream outFile("numbers.txt");
if (outFile.is_open()) {
for (int i = 0; i <= 10; i++) {
outFile << i << ' ';
}
outFile.close();
}
int sum = 0;
ifstream inFile("numbers.txt");
if (inFile.is_open()) {
int number;
while (inFile >> number) {
sum += number;
}
inFile.close();
}
cout << "Sum: " << sum << endl;
Online Demo