1

我在 Stroustrup 的 TCPPPL 中遇到了以下程序:

int main()
{
    string from, to;
    cin >> from >> to;  // get source and target file names

    ifstream is {from};  // input stream for file "from"
    istream_iterator<string> ii {is};  // input iterator for stream
    istream_iterator<string> eos {};  // input sentinel

    ofstream os{to};    // output stream for file "to"
    ostream_iterator<string> oo {os,"\n"};   // output iterator for stream

    vector<string> b {ii,eos};  // b is a vector initialized from input [ii:eos)
    sort(b.begin(),b.end());   // sor t the buffer

    unique_copy(b.begin(),b.end(),oo);// copy buffer to output, discard //replicated values
    return !is.eof() || !os; // return error state (§2.2.1, §38.3)
}

我的问题是最后一行是什么,即return !is.eof() ||!os;在做什么。我知道如果 main 返回非零值,那么这意味着一个错误,但这里返回的是什么?

4

6 回答 6

2
!is.eof()

返回您是否不在正在阅读的文件的末尾(因此true不在末尾和false末尾)和

!os

返回您的输出文件是否不可写。换句话说,这个程序返回:

  1. true当您尚未到达输入文件的末尾时(无论 2.)
  2. true当输出文件不可写时(不管 1.)
  3. false当您位于文件末尾并且输出文件可写时。
于 2018-05-15T10:09:30.817 回答
0

该程序在文件中输出在输入文件中找到的单词的有序列表,成功返回 0 或失败返回 1。

这个程序的目的是展示如何使用强大的迭代器来简明地实现一个常见问题。

  • istream_iterator< std::string >允许以单词读取文件(又名文件输入流),即使用空格字符作为分隔符。vector< string > b {ii,eos};通过迭代文件迭代器来初始化向量。这就是将文件内容加载到内存中的方式。

  • ostream_iterator< string> oo {os,"\n"};允许使用换行符作为分隔符写入输出流(此处为文件流)

  • is.eof()如果文件不在末尾,则为假,这意味着该文件尚未被读取

  • !os 是输出流的负数运算符,如果发生错误则返回 true。可能会发生错误,但这意味着不会创建输出文件。
于 2018-05-15T11:12:28.067 回答
0

如果main函数成功完成,那么它将返回0,否则返回任何其他值。所以该行return !is.eof() || !os;正在执行以下操作:

EOF表示end of file。因此,is.eof()检查我们是否到达文件末尾。如果true返回true or non 0false or 0否则。!产生结果(inverse原因是成功main退出0)。

同样的事情适用于os. 如果os是可写的,则返回truefalse否则返回。并!做出结果inverse

所以,他们俩都必须退出0

于 2018-05-15T10:23:03.613 回答
0

!is.eof()告诉从输入流读取是否到达文件末尾(因此在出现读取问题的情况下表达式为真)。

!os,它使用!运算符的重载,在出现书写问题时为真。

于 2018-05-15T10:09:56.850 回答
0

is.eof()true如果 . 发生文件结束则返回is
这很简单。

os是一个具有 的std::ostream对象operator bool()。这意味着os可以隐式转换为bool. 完成后,true如果流没有错误,则返回。

该语句!is.eof() || !os是程序的状态。
它可以翻译成:

either the eof is not occurred for `is` OR `os` has some errors

这可以进一步翻译(使用德摩根定律):

eof is occured for `is` AND `os` has no errors

这意味着如果输入流被完全读取并且输出被正确写入并且没有错误,则程序是成功的。

于 2018-05-15T10:24:47.587 回答
-1

如果你打破返回线很容易,你知道它返回非零错误,所以这是一个加号。

!is.eof() || !os;

eof 表示“文件结尾”,因此第一部分为“如果它不在文件末尾”,第二部分表示“如果没有文件”,因为您试图将某些内容保存到文件中,但没有文件是一个错误。

因此,可以读取该行:

return not(are we in the end of the file that we are reading?) 
    or not (the output file exists?)

这样将返回输入文件结束的true,并且输出文件存在,否则返回false。

于 2018-05-15T09:56:32.943 回答