if(isspace())语句在c++中不起作用
if(isspace()) statement not working C++
我正在为我的程序编写一个函数,该函数从文本文件中读取姓和名,并将它们保存为两个字符串。但是,当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
, ispunct
或isspace
)。看看这个
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- C++Matching Brackets 2解决方案不起作用
- 为什么这段代码不起作用,我该如何解决?
- 我正在开发服务器,ip作为参数传递不起作用