Filename input and reading


/ Published in: C++
Save to your folder(s)

Use to get console input from the user for a file name (in the current directory) and read in from that file.


Copy this code and paste it in your HTML
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8.  
  9. ifstream inputFile;
  10. string line;
  11. string input;
  12.  
  13. cout << "Enter a file name to scan" << endl;
  14. cin >> input;
  15.  
  16. cout << endl;
  17. cout << "Your file was: " << input << endl;
  18.  
  19. try {
  20. inputFile.open(input.data(), ios::in);
  21. }
  22. catch (...) {
  23. cout << "File open error" << endl;
  24. }
  25.  
  26. if ( !inputFile.is_open() ) {
  27. return -1;
  28. }
  29.  
  30. while (! inputFile.eof() )
  31. {
  32. getline(inputFile, line, ' ');
  33. cout << "__________ " << line << endl;
  34. }
  35.  
  36. inputFile.close();
  37.  
  38.  
  39. cin >> input; // Just used to keep the console open in Visual C++
  40. return 0;
  41. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.