gpt4 book ai didi

c++ - if(isspace()) 语句不工作 C++

转载 作者:行者123 更新时间:2023-11-30 03:36:57 25 4
gpt4 key购买 nike

我正在为我的程序开发一个函数,该函数从文本文件中读取名字和姓氏并将它们保存为两个字符串。但是,当 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 写入输出文件,但它没有t,相反,我在控制台中得到了这个输出

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 为真(此空白字符保留在输入流中)。运算符 >> 永远不会返回空格。

关于c++ - if(isspace()) 语句不工作 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40409039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com