Reputation: 47
I've written a program that takes its first argument and reverses the letters. So, for instance:
revstr cat
Will produce tac
.
Now I want this to work when a file is redirected in. So, if filler.txt is a file containing "Now is the time for all good men to come to the aid of their country!", then:
revstr < filler.txt
Should produce:
!yrtnuoc rieht fo dia eht ot emoc ot nem doog lla rof emit eht si woN
But I don't know how to detect that such redirection is occurring!
This is what I've tried - obviously, it's no good. Where am I going wrong?
int main(int argc, char* argv[]) {
string temp,input,output;//store input from file, and get which file//
ofstream out("output.txt");
if(argc == 3)
{
if(ifstream(argv[2]))
{
input = argv[2];
ifstream in(input);
while(in.good())
{
in >> temp;
ReverseWord(temp);
cout << temp << endl;
out << temp << endl;
}
}
else
ReverseWord(argv[2]);
}
else
}
I'm fairly new to C++ and am doing my best to learn.
Upvotes: 0
Views: 1261
Reputation: 4443
There are two possible approaches for you (well, you can even support both):
revstr filename.txt
.revstr < filename.txt
, then reading from std::cin will read the contents of the file. The program never even sees the filename.You can support both by reading from an ifstream, if you get an argument, and from cin, if you don't get an argument. The function that does the reading can get the steam passed in as a generic istream&.
Upvotes: 4
Reputation: 126432
You should change your definition of your main()
function so that it accepts arguments passed from command line:
int main(int argc, char* argv[])
The first variable will hold the number of command-line arguments provided, the second is a vector whose elements are pointers to NULL-terminated strings. These strings are the command-line arguments themselves. Please keep in mind, that the first string will always be the name of the executable.
For instance, supposing the name of the file to be opened will be passed as the first argument:
int main(int argc, char* argv[])
{
std::string filename;
if (argc > 1)
{
// Oh, there's some command line arguments here...
filename = argv[0];
}
// Go on processing...
}
Upvotes: 0