C ++ ifstream ofstream实现?

时间:2013-11-19 17:33:12

标签: c++ ifstream ofstream

我一直在编写Pig Latin程序,将英语转换为pig latin,我一直在实现读取文件然后将其输出到另一个txt文件时遇到问题。

这是我到目前为止所做的,但因为

而无法编译
outputFile << pigLatin(englishWord) << ' ';

这是源代码。有什么建议让它工作?感谢

void pigLatin(string englishWord)
{
string piglatinWord;
bool truefalse = false;
int letter = 0, wordLength = englishWord.length( );

while (!truefalse && letter < wordLength) 
  {
    if (englishWord.substr(letter,1) == "a" || englishWord.substr(letter,1) == "e" ||englishWord.substr(letter,1) == "i" || englishWord.substr(letter,1) == "o" || englishWord.substr(letter,1) == "u")
        truefalse = true;
    else
        letter++; 
  }
if (letter > wordLength)
    piglatinWord = englishWord + "-way "; 
else
piglatinWord = englishWord.substr(letter, wordLength-letter) + englishWord.substr(0,letter)+ "-ay " ;
cout << piglatinWord; 
}

int main( )
{
ifstream inputFile;
inputFile.open("PigLatinIn.txt");
ofstream outputFile;
outputFile.open("PigLatinOut.txt");
string englishWord, engWords;
bool done = false;
int location;

while(!inputFile.eof())
{
    string englishWord;
    inputFile >> englishWord;
    outputFile << pigLatin(englishWord) << ' ';
}

{
while (!done) 
  {
    location = engWords.find(" "); 
    if (location == -1)
      {
        done = true;
        location = engWords.length( );
      }
    englishWord = engWords.substr(0, location); 
    pigLatin(englishWord); 

    if (!done)
        engWords = engWords.substr(location + 1, engWords.length( ) - location + 1);
  }
}
cout << endl;
inputFile.close();
outputFile.close();
return 0;
}

1 个答案:

答案 0 :(得分:7)

您的pigLatin函数的返回类型为void,因此它不会返回您可能写入ofstream的任何内容:

outputFile << pigLatin(englishWord) << ' ';

pigLatin的返回类型更改为std::string并添加

 return piglatinWord; 

在功能结束时:

string pigLatin(string englishWord)
{
   // ... implementation here
   return piglatinWord;
}

另外,为了使您的功能更加清晰和统一,我建议您从函数中删除cout << piglatinWord;并在调用函数中输出返回值:

 englishWord = engWords.substr(0, location); 
 cout << pigLatin(englishWord);