if(isspace())语句在c++中不起作用

if(isspace()) statement not working C++

本文关键字:不起作用 c++ 语句 isspace if      更新时间:2023-10-16

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

等等……

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

抱歉,没有足够的信誉来评论它,但是有两个错误的答案。zahir的评论是对的。Std::isspace(c,is.getloc())对于is中的下一个字符c为true(该空白字符保留在输入流中)。

您正在检查next是否为for循环中的大写字符:for(; isalpha(next) && i < 3; in >> next)
根据文档,在默认的C语言环境中,"空格"字符不被视为字母字符。您可以更改语言环境来解决这个问题,或者(在我看来)更可取的是,修改for循环以接受空格。
for(; (isalpha(next) || isspace(next)) && i < 3; in >> next)这样的东西应该允许循环处理空格和字母

编辑:正如其他几个人指出的那样,我忽略了这样一个事实,即在这里使用>>操作符将导致您从一开始就看不到空白,因此我的回答不完整。我将保留它,以防它仍然有用。

默认为operator>>将忽略所有空白字符,但您可以使用操纵符noskipws来规避此行为,如下所示:

in >> noskipws >> next;

您的问题不是isspace功能,而是您的for循环,您强制for循环仅通过使用isalpha来处理字母字符,在这种情况下,字符不能是iscntrl, isdigit, ispunctisspace)。看看这个