我在之前的堆栈问题中找到了这个潜在的解决方案。我的问题是它没有输出到文件。
该程序终止而没有错误,并且实际上做了它应该做的事情,因为我已经用cout
.
该程序接受一个 7 位数的电话号码。然后将所有可能用这 7 位数字组成的单词写入文件,尊重标准电话上的字母数字关联。
程序使用两个函数:main
和wordGenerator
包含iostream, fstream, & cstdlib
main
:
int main()
{
int phoneNumber[ 7 ] = { 0 }; // holds phone number
// prompt user to enter phone number
cout << "Enter a phone number (digits 2 through 9) " << "in the form: xxx-xxxx\n";
// loop 8 times: 7 digits plus hyphen;
// hyphen is not placed in phoneNumber
for ( int u = 0, v = 0; u < 8; u++ )
{
int i = cin.get();
// test if i is between 0 and 9
if ( i >= '0' && i <= '9' )
phoneNumber[ v++ ] = i - '0';
} // end for
wordGenerator( phoneNumber ); // form words from phone number
} // end main
wordGenerator
:
void wordGenerator( const int * const n )
{
cout << "Some Word Forming Magic is going on!" << endl;
// set output stream and open output file
ofstream outFile("phone.dat");
// letters corresponding to each number
const char * phoneLetters[] = {"___", "___", "ABC", "DEF", "GHI", "JKL", "MNO", "PRS", "TUV", "WXY"};
// terminate if file could not be opened
if ( !outFile )
{
cerr << "File could not be opened! Program Terminating..." << endl;
exit(1);
}
int count = 0; // number of words found
// output all possible combinations
for ( int i1 = 0; i1 <= 2; i1++ )
{
for ( int i2 = 0; i2 <= 2; i2++ )
{
for ( int i3 = 0; i3 <= 2; i3++ )
{
for ( int i4 = 0; i4 <= 2; i4++ )
{
for ( int i5 = 0; i5 <= 2; i5++ )
{
for ( int i6 = 0; i6 <= 2; i6++ )
{
for ( int i7 = 0; i7 <= 2; i7++ )
{
/* I think the next 8 lines is what's not working! */
/* Write a series of cascaded stream insertion operations
to output a set of seven letters to outFile, followed by a space */
outFile
<< phoneLetters[n[0]][i1]
<< phoneLetters[n[1]][i2]
<< phoneLetters[n[2]][i3]
<< phoneLetters[n[3]][i4]
<< phoneLetters[n[4]][i5]
<< phoneLetters[n[5]][i6]
<< phoneLetters[n[6]][i7]
<< " ";
if ( ++count % 9 == 0 ) // form rows
outFile << '\n';
}
}
}
}
}
}
}
//alert user that wordGenerator has completed
cout << "Writing to file..." << endl;
// output phone number
outFile << "\nPhone number is ";
for ( int i = 0; i < 7; i++ )
{
if ( i == 3 )
outFile << '-';
outFile << n[ i ];
} // end for
//print results to screen
cout << count / 9 << " words were created from" << endl;
//close output file
outFile.close();
} // end function wordGenerator
程序运行良好。没有错误,除了没有写入输出文件phone.dat