/*
Practice Coding Exercises
Using command line arguments read in the file called Horoscope.txt
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
usingnamespace std;
//A function which gets a word from the stream and returns the stream to the call
istream& getword(istream& is, string& word)
{
char ch;
while (is.get(ch))
{
if (isalpha(ch))
break;
}
//'’'
if (!is)
return is;
string buffer;
buffer += ch;
while (is.get(ch))
{
if (isalpha(ch))
buffer += ch;
elsebreak;
}
if (is)
is.unget();
if (is.eof())
is.clear(ios::eofbit);
word = std::move(buffer);
return is;
}
int main(int argc, char* argv[])
{
//1. Read in the filename and open an input filestream
ifstream inFile(argv[1]);
//Test for success
if (!inFile)
{
cerr << "Input file opening failed.\n";
return EXIT_FAILURE;
}
//2. Get the words from the file and store in a vector
vector<string> v;
string word;
while (getword(inFile, word))
v.push_back(word);
//Finished reading in file
cout << "Finished reading in file!\n";
}
i understand that if u use cin , unget will put the character back into the stream, but i still don't understand if i combine unget with infile like infile.unget() . will it still put the last character back into the stream ?
i can comment out this section of code and i tried running without it and it has no effect:
It has no effect because it is guaranteed that is (line 40) will return false and hence is.unget(); will not be called. But I would think it has no effect anyway since the stream is in an error state. What is the effect you want?
if unget puts the char back into the stream again for read, would not i read the same char twice
at the line while (is.get(ch)) ?
No, because it is not inside the loop. If it where inside you would read the same character over and over again which would lead to a infinite loop if the character where actually alpha.