テキストファイルから姓と名字を読み込んで2つの文字列として保存するプログラムの関数を作成しています。しかし、for-loopが最初と最後の間の最初のスペースに達したときに実行するif(isspace(next))文を取得できません。ここでif(isspace())文が動作しないC++
は完全なプログラムは、私がトラブルを抱えていたコードのセクションでは、コードは(私の心の中で)ファイルから各文字を読むことになっている
if(isspace(next))
{
cout << "Space!" << endl;
out << firstname << ' ';
i++;
}
ある
#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++;
}
}
}
}
です文字列に追加してスペースに達すると、その文字列ファーストネームが出力ファイルに書き込まれますが、代わりにこの出力がコンソールに表示されます
名前はヘスダムことになっているか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
等...
お知らせ....と何が起こることになっていることは、それはFIRSTNAMEとダムにヘスを保存している...姓へ。代わりに、ファーストネーム文字列の最後の名前の後ろのタブまですべてを追加するだけで、出力ファイルには書き込まれません。 (isalpha(next)から)forループを終了するが何らかの理由でisspace(next)引数が機能しないため、タブを読み込みます
私が知っている限り、 'in >> next'はあなたに空白を与えません。 [ここ](http://en.cppreference.com/w/cpp/string/basic_string/operator_ltltgtgt)に記載されています。最初は空白をスキップし、空白で止まります。 – zahir