我正在为我的程序编写一个函数,该函数从文本文件中读取名字和姓氏并将它们保存为两个字符串。但是,当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++;
        }

代码应该(在我看来)从文件中读取每个字符并添加到字符串中,一旦到达空格,则将该字符串名写入输出文件,但是没有,相反,我在控制台中获得了此输出
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

等等...

请注意,该名称应该是Hess Dam ....,应该发生的是它将Hess保存为firstname,将Dam ....保存为lastname。相反,它只是将整个内容添加到名字字符串中姓氏后面的制表符之前,并且永远不会写入输出文件。它读取选项卡,因为它退出for循环(从isalpha(next)开始),但由于某些原因,isspace(next)参数不起作用

最佳答案

抱歉,没有足够的信誉来发表评论,但是有两个错误的答案。扎希尔的评论是正确的。 std::isspace(c,is.getloc())对于in中的下一个字符c为true(此空白字符保留在输入流中)。运算符>>绝不会返回空格。

09-06 22:58