I am working on a function for my program that reads the first and last name from a text file and saves them as two strings. However, I cannot get the if(isspace(next)) statement to execute when the for-loop reaches the first space in between the first and last names.
Here is the full program
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <ctype.h>
using namespace std;
void calcAvg(ifstream& in, ofstream& out);
int main()
{
//open input and output file streams and check for any failures
ifstream input;
ofstream output;
input.open("lab08_in.txt");
output.open("lab08_out.txt");
if(input.fail())
{
cout << "Error: File not Found!" << endl;
exit(1);
}
if(output.fail())
{
cout << "Error: File creation failed!" << endl;
exit(1);
}
calcAvg(input, output);
return 0;
}
void calcAvg(ifstream& in, ofstream& out)
{
int sum = 0;
double average;
//save first and last name to strings
string firstname, lastname;
char next;
int i = 1;
in >> next;
for(; isalpha(next) && i < 3; in >> next)
{
if(i == 1)
{
firstname += next;
cout << next << " was added to firstname" << endl;
if(isspace(next))
{
cout << "Space!" << endl;
out << firstname << ' ';
i++;
}
}
else if(i == 2)
{
lastname += next;
cout << next << " was added to lastname" << endl;
if(isspace(next))
{
cout << "Space!" << endl;
out << lastname << ' ';
i++;
}
}
}
}
The section of code that I am having troubles with is
if(isspace(next))
{
cout << "Space!" << endl;
out << firstname << ' ';
i++;
}
The code is supposed to (in my mind) read each character from the file and add to the string and once it reaches a space write that string firstname to the output file, but it doesn't, instead I get this output in the console
H was added to firstname
e was added to firstname
s was added to firstname
s was added to firstname
D was added to firstname
a was added to firstname
m was added to firstname
etc...
Notice how the name is supposed to be Hess Dam.... and what is supposed to happen is it saves Hess to firstname and Dam... to lastname. Instead it is just adding the whole thing up until the tab after the last name in the firstname string and it never writes to the output file. It reads the tab because it exits the for loop (from the isalpha(next)) but the isspace(next) argument doesn't work for some reason