The code below reads my file that has 5 names. How would I get the output to show all the names and tell me "The first person is..." and "The last person is..." How would I make the output say that?
bool first{ true };
std::getline(myfile, line);
while (1)
{
if (!myfile)
{
std::cout << "The last person is: " << line << std::endl;
break;
}
if (first)
{
first = false;
std::cout << "The first person is: " << line << std::endl;
}
else
std::cout << line << std::endl;
}
std::getline(myfile, line);
}
Not 100% sure about this, but you can try it while I test it.
int main()
{
std::string line;
std::ifstream myfile("student.txt");
bool first{ true };
size_t count{ 1 };
if (myfile.is_open())
{
while (std::getline(myfile, line))
count++;
myfile.clear();
myfile.seekg(0);
for (size_t lc = 1; lc < count; lc++)
{
std::getline(myfile, line);
if (lc == count - 1)
{
std::cout << "The last person is: " << line << std::endl;
break;
}
if (first)
{
first = false;
std::cout << "The first person is: " << line << std::endl;
}
else
std::cout << line << std::endl;
}
}
else
std::cout << "Unable to open file";
myfile.close();
}
If I understand correctly I think this is what you want. If not let me know.
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::ifstream myfile("student.txt");
if(!myfile) {
std::cout << "Can't open input file.\nExiting now.\n";
return 0;
}
std::string ... // you need to store the value for first person,
// last person and the line you read at each iteration
while(std::getline(myfile, /* store inside the std::string for the line */))
{
if( ??? ) // check if you've already saved something in the
{ // std::string for the first person name
// if not, save the first person name from the line
}
if(!line.empty()) { // if this is *NOT* the last loop iteration
// save the last person name
}
std::cout << /* std::string for the line */ << '\n';
}
std::cout << "The first person is " << // std::string for the first person
<< "\nThe last person is " << // std::string for the last person
<< '\n';
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
string first, last, line;
ifstream myfile( "student.txt");
if ( myfile.is_open() )
{
getline( myfile, first );
while ( getline( myfile, line ) ) last = line;
myfile.close();
cout << "The first name is " << first << '\n';
cout << "The last name is " << last << '\n';
}
else
{
cout << "Unable to open file";
}
}