-
April 12th, 2010, 12:12 PM
#1
How to input name of data file
I'm trying to create a program that opens a data file. I want the user to input the name of the data file, and the have the program open it up. However, I'm having trouble getting this too work. Here is what I have so far:
Code:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
// Initializes variables
double x1, x2, x3;
string file1;
cout<<"Enter name of first data file: "; //Input name of data file
cin>>file1;
// Opens data file
ifstream infile;
infile.open(file1); // Should open data file (does not)
if(!infile)
{
cout<<"Unable to open file: "<<file1<<"\n"<<endl; // Displays error message if data file cannot be opened
system("pause"); // Pauses command window
exit (0); // Exits program
}
else
{...
-
April 12th, 2010, 12:17 PM
#2
Re: How to input name of data file
open wants as const char *
Code:
infile.open(file1.c_str()); // this will open data file
Kurt
-
April 12th, 2010, 12:18 PM
#3
Re: How to input name of data file
To use a null terminated string given a std::string, use the c_str() member function, e.g.,
Code:
ifstream infile(file1.c_str());
-
April 12th, 2010, 12:23 PM
#4
Re: How to input name of data file
Is there anything else I need to change? Because I still get the error message I put in:
Code:
Unable to open file: DataFile1
ie. Do I still initialize file1 as a string?
Last edited by chara76; April 12th, 2010 at 12:25 PM.
-
April 12th, 2010, 12:29 PM
#5
Re: How to input name of data file
Ah, but now you have fixed the syntax error. It may be the case that the file does not exist, e.g., because you specified a wrong name.
-
April 12th, 2010, 12:34 PM
#6
Re: How to input name of data file
Thanks, you were right. I wasn't typing .txt at the end of the file name
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|