I need to do this: Open a user-specified file for input. Prompt for the name of the file, read it into a string variable, echo print it to the terminal and then open it. If the file is not successfully opened, enter into a loop that prints out an error message, resets the input file stream variable (Input_file_stream_var.clear(); Where Input_file_stream_var is the name of your input file stream variable), obtains a new file name and tries to open the new file. The loop continues until the user successfully enters a valid file name or presses ctrl-c to exit.
and here is the code that i have so far but i cant get it to loop back into the process if the file was not opened.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
// Variables
char test;
string infname, outfname;
fstream infile, outfile;
do
{
// Propt for and echo print input file
cout << endl << "Enter the name of the input file: ";
cin >> infname;
cout << infname << endl;
infile.open(infname.c_str());
// Test if file opened
if(!infile)
{
cout << string(12,'*') << " File Open Error " << string(12,'*') << endl;
cout << "==> Input file failed to open properly!!\n";
cout << "==> Attempted to open file: " << infname << endl;
cout << "==> Please try again...\n";
cout << string(41,'*') << endl;
infile.clear();
return 1;
}
} while(!infile.is_open());
return 0;
}
The return 1 statement is causing your program to exit: you are returning from main()
Just don't do that.
Try removing the return 1 or changing it to continue. return 1 returns code execution from main and not the loop.
Related
I'm confused about how to open/access a file using Notepad++ and the cmd with MinGW compiler. I understand the file needs to be in the same scope however, I'm not sure where. I have tried placing the .txt file in my Documents folder which also holds the main.cpp file, and I have tried placing it in the bin folder of the MinGw folder. When I run the code, I get the error message. Is something wrong with my code or is the .txt file in the wrong location?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFS;
ofstream outFS;
string fileName;
double fileNum;
//fileName = "input_prac.txt";
//cout << "Enter file name: " << endl;
//cin >> fileName;
cout << "Opening file..." << endl;
inFS.open("input_prac.txt"); // Open file
if (!inFS.is_open())
{
cout << "Could not open file" << endl;
exit(1);
}
// Read file
while(!inFS.eof())
{
inFS >> fileNum;
cout << fileNum << endl;
}
inFS.close(); // close file
return 0;
}
I'm just learning and practicing the basics of ifstream objects and tried to write a small program that will read a .txt file and then display what is read. I can't tell what I need to change, but i do know that there might be something wrong with how I'm specifying the path because. When I run the program, it doesn't seem like it can open the file. the friends.txt file I made is in the path I specified. In the .txt file, there are 3 names which are written on 3 consecutive lines (after typing one name, I pressed enter to write another name on a new line).
I tried checking to see if made any typos on the folder names in the path and made sure to correct any I found.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inputfile;
string name;
inputfile.open("C:\\Users\\Dox\\Documents\\Visual Studio 2015\\Projects\\Practice\\Practice\\friends.txt");
cout << "Reading data from the file.\n";
if (!inputfile.is_open())
{
cout << "error opening file" << endl;
}
else
{
inputfile >> name;
cout << name << endl;
inputfile >> name;
cout << name << endl;
inputfile >> name;
cout << name << endl;
}
inputfile.close();
cin.get();
return 0;
}
When running the code, the error message I made displays.
I am writing a program that needs to read in a list of 11,000 numbers from a text file and then output them to the console. However, whenever I run my code, I have been able to pinpoint that it only prints the last 299 numbers. Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
double dataVector[11000]; //text file has 11,000 elements
string userfile; //name of file selected by user
//prompt user for file to be opened
cout << "Enter the name of the file you would like to read :: ";
cin >> userfile;
ifstream ifs(userfile); //open file
if (!ifs) // return error message if file cannot be opened
{
cerr << "Error: could not find the specified file" << endl;
return 1;
}
for (int i = 0; i < 11000; i++)
{
if (ifs >> dataVector[i]) //read in array
cout << dataVector[i] << endl;
else //if element cannot be read, return error
{
cout << "Failed to read." << endl;
break;
}
}
ifs.close(); //closes the file
system("pause");
return 0;
}
Is there something that I'm missing that's causing this issue? My code is not returning any compiler errors, no errors from my checks, and my text file IS in the right location.
I am trying to create a very simple program that writes to a file, but can't understand why it won't let me write to a file if I put it within an if statement! Here's the code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
void readFile();
int main()
{
string line;
string today;
string readOrWrite;
cout << "Do you want to write to a file or read a file? " << endl;
cout << "Type \"write\" or \"read\" ";
cin >> readOrWrite;
if (readOrWrite == "read")
{
readFile();
}
else if (readOrWrite == "write")
{
cout << "How are you today? " << endl;
getline(cin, today);
ofstream myJournal;
myJournal.open("Journal.txt", ios::app);
myJournal << today << " ";
myJournal.close();
}
else
{
return 0;
}
return 0;
}
void readFile()
{
ifstream myJournal;
myJournal.open("Journal.txt");
string line;
if (myJournal.is_open())
{
while (getline(myJournal, line))
{
cout << line << endl;
}
myJournal.close();
}
else
{
cerr << "Error opening file ";
exit(1);
}
}
When I move it out of the if statement, it works smoothly and is able to write to the file, but when I place it inside, it opens the program, asks me the "Do you want to write to a file or read a file? ", I type "write", then it says "How are you today? " and then ends the program, printing "Press any key to continue...". Any help?
it says "How are you today? " and then ends the program, printing "Press any key to continue...". Any help?
std::istream::ignore should help in that case you are encountering.
cout << "How are you today? " << endl;
cin.ignore(10, '\n'); // Inserted
getline(cin, today);
Why do we need that in between?
It takes out 10 characters, which is enough amount of length, from the buffer and stops if it encounters a newline, which is '\n'. (Remember that you press the key 'enter' after typing "wrtie")
By doing so you can move on to the next new line, preventing std::cin from any parse failure.
More info : http://www.cplusplus.com/reference/istream/istream/ignore/
I'm quite new to C++ programming, and I'm having trouble reading from an already open file. What I'm doing is writing to a file, reading from it, adding to the end of it, and then trying to read from it again without having to close the original ifstream. The code is as follows:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream myFile ("example.dat");
// Open and write to file
if (myFile.is_open())
{
myFile << "This is a line." << endl;
myFile << "This is another line." << endl;
myFile.close();
}
else cout << "no";
// Open and read from file
string line;
ifstream myFilein ("example.dat");
if (myFilein.is_open())
{
while (getline(myFilein,line))
{
cout << line << myFilein.tellg() << endl;
}
//myFilein.close();
}
// Open and add to end of file
if (!myFile.is_open())
{
myFile.open("example.dat", ios::app);
myFile << "This is the last line." << endl;
myFile.close();
}
//myFilein.open("example.dat", ios::ate);
// Read from already open file
myFilein.seekg(0, ios::beg);
if (myFilein.is_open())
{
cout << "myFilein is open. " << myFilein.tellg() << endl;
while (!myFilein.eof())
{
getline(myFilein, line);
cout << line << endl;
}
}
myFilein.close();
int holdClose;
cin >> holdClose;
return 0;
}
Obviously, something is going wrong, as tellg() is returning a value of -1 after the initial read (i.e., after it hits the end of the file), but I'm not entirely sure why it's returning -1, since I'm trying to reset the position to the beginning of the file. Is there something I'm missing or misunderstanding about how this works? If I close and re-open the file, then it's fine, but I'm curious if there's a way to keep reading from it without having to close it, if that makes sense. Thank you for your help :)
You didn't clear the state of the stream, thus the seekg call did nothing. You need to add myFilein.clear() before the repositioning.