getline()的实际行为如何? [英] How does getline() actually behave?

查看:26
本文介绍了getline()的实际行为如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个问题:

  1. 如果while循环结束后再次执行"getline(in,line)",则s会发生什么?

  1. What happens to s if I again do a "getline(in,line)" after the while loop ends?

ifstream in("string.txt");
string s, line;
s = "";
while(getline(in,line))
{

    s = s + line + "\n";

}

cout<<s<<endl<<"******************************************"<<endl;

  • getline()函数:每次调用它时,它是否都进入上述代码中ifstream"in"对象的"next"行?如果是这样,当while循环结束并且我再次调用同一个函数时会发生什么?(与第一个问题几乎相同,只是有细微的差别)

  • The getline() function: everytime it is called, does it goes to the "next" line of the ifstream "in" object in the above code? If so what happens when the while loop ends and I call the same function again? (almost the same as first question, just a subtle difference)

    推荐答案

    如果while循环结束后再次执行"getline(in,line)",那么s会发生什么?

    What happens to s if I again do a "getline(in,line)" after the while loop ends?

    std :: getline()返回类似于布尔值 false 的内容时,循环结束.当您查看函数的签名时,您会看到它返回流.流有隐式转换为类似于其状态的类似布尔的形式.如果 if(stream)将流评估为 false ,则意味着该流处于不良状态.这可以是EOF标志集,也可以是错误标志之一,或者两者都可以.
    任何使用处于不良状态的流的尝试都将失败.什么都不会读.

    The loop ends when std::getline() returns something that resembles a boolean false. When you look at the signature of the function you will see that it returns the stream. Streams have an implicit conversion to something boolean-like that resembles their state. If if(stream) evaluates the stream to false, then that means that the stream is in a bad state. This could be the EOF flag set or one of the error flags, or both.
    Any attempt to use a stream that is in a bad state will fail. Nothing will be read.

    getline()函数:每次调用它时,它是否都进入上述代码中ifstream"in"对象的"next"行?如果是这样,当while循环结束并且我再次调用同一个函数时会发生什么?(与第一个问题几乎相同,只是细微的差别)

    The getline() function: everytime it is called, does it goes to the "next" line of the ifstream "in" object in the above code? If so what happens when the while loop ends and I call the same function again? (almost the same as first question, just a subtle difference)

    这与 std :: getline()没有关系.打开的文件中的位置是(文件)流的属性.每次(重新)打开文件进行读取(不传递用于设置位置的额外参数)时,该位置都将设置为流(文件)的开头.

    This has nothing to do with std::getline(). The position in the opened file is a property of the (file) stream. Every time you (re-)open the file for reading (without passing extra parameter for setting the position), the position is set to the beginning of the stream (file).

    这篇关于getline()的实际行为如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆