really easy c++: Does the operator >> in fstream remove newline characters after reading something?

孤者浪人 提交于 2019-12-10 10:28:45

问题


// file.in
12
13

// main.cpp
fstream f("file.in", ios::in);
int n;
char c;
f >> n;
f.get(&c);

After extracting the number 12, what is the next character? Is it newline or '1'? If I call getline instread of get, do I get an empty line or '13'?


回答1:


It leaves the delimiter in the input buffer, so the next character you read will be a new-line. Note, however, that most extractors will skip white space (which includes new-line) before anything they extract, so unless you do call something like getline this won't usually be visible.

Edit: to test on something like ideone, consider using a stringstream:

#include <sstream>
#include <iostream>

int main(){ 
    std::istringstream f("12\n13");
    int n;
    char c;
    f >> n;
    f.get(c); // get takes a reference, not a pointer. Don't take the address.

    std::cout << "'" << c << "'";
    return 0;
}

I wouldn't expect to see a difference between a stringstream and an fstream in something like this.



来源:https://stackoverflow.com/questions/10842545/really-easy-c-does-the-operator-in-fstream-remove-newline-characters-after

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!