C++;初级读物第五版:单词转换程序 第11章,从C++入门5版,标题“Word TrimeStudio”,它有一个函数,叫做“代码> WorddTrimeToor()/,定义如下: void word_transform(ifstream &map_file, ifstream &input) { auto trans_map = buildMap(map_file); // store the transformations string text; // hold each line from the input while (getline(input, text)) { // read a line of input istringstream stream(text); // read each word string word; bool firstword = true; // controls whether a space is printed while (stream >> word) { if (firstword) firstword = false; else cout << " "; // print a space between words // transform returns its first argument or its transformation cout << transform(word, trans_map); // print the output } cout << endl; // done with this line of input } }

C++;初级读物第五版:单词转换程序 第11章,从C++入门5版,标题“Word TrimeStudio”,它有一个函数,叫做“代码> WorddTrimeToor()/,定义如下: void word_transform(ifstream &map_file, ifstream &input) { auto trans_map = buildMap(map_file); // store the transformations string text; // hold each line from the input while (getline(input, text)) { // read a line of input istringstream stream(text); // read each word string word; bool firstword = true; // controls whether a space is printed while (stream >> word) { if (firstword) firstword = false; else cout << " "; // print a space between words // transform returns its first argument or its transformation cout << transform(word, trans_map); // print the output } cout << endl; // done with this line of input } },c++,C++,如您所见,该函数工作正常。请帮助我是否正确或使用了本书的功能 当然,您的方式会打印所有由空格分隔的变换(word,trans\u map)。但是,您也会在末尾打印一个多余的空格,这可能会有问题,也可能不会有问题。您会添加一个尾随space@StoryTeller:对不起。“我不明白。”说书人:谢谢!我现在知道了。@StoryTeller:在函数中:没有关闭文件的功能,所以我应该关闭它们吗input.close()…你知道我总是努力理解每件事,尤其是我自己在学习。这是最好的方法。好的。最后一件事是

如您所见,该函数工作正常。请帮助我是否正确或使用了本书的功能


当然,您的方式会打印所有由空格分隔的
变换(word,trans\u map)
。但是,您也会在末尾打印一个多余的空格,这可能会有问题,也可能不会有问题。

您会添加一个尾随space@StoryTeller:对不起。“我不明白。”说书人:谢谢!我现在知道了。@StoryTeller:在函数中:没有关闭文件的功能,所以我应该关闭它们吗
input.close()…
你知道我总是努力理解每件事,尤其是我自己在学习。这是最好的方法。好的。最后一件事是这个程序不能关闭文件。我应该给他们打电话吗
input.close()
当我读完它们时?否,
std::ifstream
的析构函数关闭(调用
close()
)文件。因此显式调用
close
是不安全的?
void word_transform(ifstream &map_file, ifstream &input)
{
    auto trans_map = buildMap(map_file); // store the transformations
    string text; // hold each line from the input
    while (getline(input, text)) { // read a line of input
        istringstream stream(text); // read each word
        string word;

        while (stream >> word)
            cout << transform(word, trans_map) << " ";
        cout << endl; // done with this line of input
    }
}