繁体   English   中英

C++ 入门第 5 版:单词转换程序

[英]C++ primer 5th Ed: The Word Transformation Program

在 C++ Primer 5 Edition 的第 11 章中,标题“单词转换程序”有一个名为word_transform()的 function,它是这样定义的:

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
    }
}
  • 如果我没有错的话,我看到 Boolean firstword第一个字在这里是多余的,不需要检查空格,而是在调用transform_word之后返回转换后的文本或原始文本,然后打印它并简单地在它后面打印一个空格:

     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 } }
  • 如您所见,function 工作正常。 请帮助我是否正确或使用本书的 function。

当然,您的方式打印所有由空格分隔的transform(word, trans_map) 但是您最后还会打印一个多余的空间,这可能会或可能不会引起关注。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM