I am doing exercises from Bjarne Stroustrup's book, Programming Principles and Practice Using C++. I am on the first exercise in Chapter 10, where it says to write a program that produces the sum of all the numbers in a file of whitespace-separated integers. I based my code below on what's used for Exercise 2 of Chapter 10.5. I get an error when the ifstream
object is created. Here is the code I am trying to run:
#include "../../std_lib_facilities.h"
int main(int argc, const char * argv[]) {
// insert code here...
cout << "Plese enter the input file name: " << endl;
string iname;
cin >> iname;
ifstream ist {iname};
if (!ist) error("Can't open input file ",iname);
vector<int> numbers;
int sum;
int n;
while(ist>>n) {
numbers.push_back(n);
}
for (int i=0; i<numbers.size(); ++i) {
sum += numbers[i];
}
cout << sum << endl;
return 0;
}
Any input I enter is getting error. I tried myin, myin.txt or any other name. The error("Can't open input file ",iname);
is from the library created by the author.
I know the file does exist in the same directory with main.cpp and created with TextEdit from Mac using the format for plain text.
[...] in the same directory with main.cpp [...]
It does not really matter where you put the input file relative to the source file. The file should be in the environment's current working directory when you run the program.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments