真正容易c ++:操作符>>在fstream中读取东西后删除换行符? [英] really easy c++: Does the operator >> in fstream remove newline characters after reading something?

查看:555
本文介绍了真正容易c ++:操作符>>在fstream中读取东西后删除换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// file.in
12
13

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

提取数字12后,下一个字符是什么?是换行还是1?如果我调用get的getline instread,是否得到一个空行或'13'?

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'?

推荐答案

输入缓冲区,所以你读的下一个字符将是一个新行。但是,请注意,大多数提取器会跳过它们提取的任何内容之前的空格(其中包括换行符,所以除非你调用类似 getline 这通常不会显示。

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.

编辑:测试像ideone, code> stringstream :

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;
}

我不希望看到一个 stringstream fstream

这篇关于真正容易c ++:操作符&gt;&gt;在fstream中读取东西后删除换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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