【发布时间】:2017-07-11 06:21:40
【问题描述】:
我试图构建一个读取现有文本文件的程序。长度为 5 和 10 个字符的单词会保存在一个新文件中。我构建了这个程序,它使用 if 语句运行良好,但我应该使用函数void FindTenAndFiveLetterWords(string word)。我对函数还不满意,所以我非常感谢你对如何使用函数来构建这个程序的帮助。
这是我没有函数的代码。
include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string word;
ifstream openFile;
openFile.open ("WordList.txt");
ofstream newFile ("List.txt");
if (!openFile.is_open())
{
cout <<"Couldn't open the file" <<endl;
return 0;
}
while (openFile >> word)
{
int wordLength10 = 10;
int wordLength5 = 5;
if (word.length() == wordLength10)
{
newFile << word << ' ';
}
else if (word.length() == wordLength5)
{
newFile << word << ' ';
}
}
openFile.close();
newFile.close();
return 0;
}
【问题讨论】:
-
您需要学习如何编写函数。就是这样。
-
如何通过函数签名传递文件名
标签: c++ function file input output