c++ - Cannot find input file -


this question exact duplicate of:

i trying create program asks user name of file, opens file, adds sum of integers listed on file, writes sum on output file.

after writing code , saving testfile1.txt same folder program, program keeps giving me the: "could not access testfile1" (message output notify myself unable open testfile1.txt).

here have far (skipped lines description blocks):

#include <iostream> #include <fstream> #include <string> using namespace std;  int main(){     ifstream inputfile;     ofstream outputfile;      string testfile1;     string sum;      int total = 0;     int num;      cout << "please input name of file." << endl;     cin >> testfile1;     cin.get();      inputfile.open(testfile1.c_str());      if (inputfile.fail()) {         inputfile.clear();         cout << "could not access testfile1" << endl;         return(1);     }      while (!inputfile.eof()) {         inputfile >> num;         total = total + num;         inputfile.close();     }      outputfile.open(sum.c_str());     outputfile << total << endl;     outputfile.close();      if (outputfile.fail()) {         cout << "could not access file." << endl;         return 1;     }      return 0; } 

question:

how can make program find , open testfile1.txt?

note:

i pretty sure when prompted file name, did not misspell.

here few remarks figure out possible problem:

1.you reduce lines of code attaching streams file during definition, instead of defining them , use open, so:

ifstream inputfile(testfile1.c_str()); 

2.to check if file open (and handle if couldn't):

 if (!inputfile) error ("can't open input file: ", testfile1); 

and:

 if (!outputfile) error ("can't open output file: ", sum); 

right after definition.

3.all open files implicitly closed @ end of program (or function contains them), there no need explicitly close() them.

4.to read contents of input file , sum them:

int sum = 0; string line; // read line while (getline(inputfile, line)) {     stringstream ss(line);     // assuming reading integers separated white space     int num  = 0;     // extract each number on line     while (ss >> num) total += num;     // reset line     line.erase(); } 

note: test , modify code according specific needs. side note: omit: cin.get(); in code.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -