Sep 23, 2016 at 7:29pm UTC
The user inputs the name of the txt file, not the name of the ifstream object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cctype> //for isspace
using namespace std;
int main(int argc, char * argv[])
{
string fileName;
string content;
cout << "Enter a file name.\n" ;
cin >> fileName;
ifstream infile(filename);
return 0;
}
Last edited on Sep 23, 2016 at 7:30pm UTC
Sep 27, 2016 at 1:05am UTC
Thank you. What does the infile function do? I tried searching for it in the c++ reference tab but couldn't find it. Is it the same as fileName.open?
Sep 27, 2016 at 1:24am UTC
infile is not a function, its the name of the ifstream object. The code below is equivalent to the one I have in my previous post.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cctype> //for isspace
using namespace std;
int main(int argc, char * argv[])
{
string fileName;
string content;
cout << "Enter a file name.\n" ;
cin >> fileName;
ifstream infile; // declare file
infile.open(filename); // open file using user-inputted filename
return 0;
}
Last edited on Sep 27, 2016 at 1:24am UTC
Sep 27, 2016 at 1:51am UTC
Basically if your assignment is not about 'how to read / write file', you don't have to work on the files.
You could just write the program as it reads text from user input, and then use pipe to send the text fie as user input.
For example, after you build your 'myassignment.exe', you could just run it like this:
myassignment.exe < myinput.txt
Sep 30, 2016 at 9:38pm UTC
Now I'm having trouble copying the text from the file into a string. I'm probably not doing it right.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include <iostream>
#include <fstream>
#include <string>
#include <queue>
#include <vector>
#include <cctype>
using namespace std;
int main(int argc, char * argv[])
{
if (argc != 2)
cout << "usage: " << argv[0] << endl;
else
{
ifstream infile;
infile.open(argv[1]);
if (!infile.is_open())
{
cerr << "Could not open file\n" ;
return -1;
}
else
{
char x;
string word;
while (infile.get(x))
{
word << x;
}
}
}
return 0;
}
Error is on line 32.
Last edited on Sep 30, 2016 at 9:38pm UTC