我正在为我的程序开发一个函数,该函数从文本文件中读取名字和姓氏并将它们保存为两个字符串。但是,当 for 循环到达名字和姓氏之间的第一个空格时,我无法执行 if(isspace(next)) 语句。
这是完整的程序
#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++;
}
}
}
}
我遇到问题的代码部分是
if(isspace(next))
{
cout << "Space!" << endl;
out << firstname << ' ';
i++;
}
该代码应该(在我看来)从文件中读取每个字符并添加到字符串中,一旦它到达一个空格,就将该字符串firstname写入输出文件,但它没有,而是我在控制台中得到这个输出
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...
注意名字应该是 Hess Dam.... 并且应该发生的事情是将 Hess 保存到firstname和 Dam... 到lastname。相反,它只是将整个内容添加到名字字符串中姓氏之后的制表符,并且它从不写入输出文件。它读取选项卡是因为它退出了 for 循环(来自 isalpha(next))但 isspace(next) 参数由于某种原因不起作用