zoukankan      html  css  js  c++  java
  • 解决使用{freopen与 getline}读取不同文件时产生的的问题

    读取单一文件

    使用 freopen重定向。

    用 getline逐行读取,处理。

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    
    using namespace std;
    string s;
    
    int main()
    {
    	freopen("text1.in", "r", stdin);
    	while (getline(cin, s)) {
    		/* - code - */
    	}
    	fclose(stdin);
    	return 0;
    }
    
    

    读取多个文件

    基本方法同上。

    特别注意:在读取完一个文件后,

    使用 cin.clear()清空输入流。

    否则除第一个文件,其他文件无读入。

    正确示例:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    
    using namespace std;
    string s;
    
    int main()
    {
    	freopen("text1.in", "r", stdin);
    	while (getline(cin, s)) {
    		/* - code - */
    	}
    	fclose(stdin);
    	cin.clear();
    	freopen("text2.in", "r", stdin);
    	while(getline(cin, s)) {
    		/* - code - */
    	}
    	fclose(stdin);
    	// ...
    	return 0;
    }
    
    
  • 相关阅读:
    C语言文法
    实验一
    词法分析
    py中文词频统计
    py字符串练习
    py画了个国旗
    熟悉常用的Linux操作
    大数据概述
    实验三、 递归下降分析程序实验
    简易c语言LL(1)文法
  • 原文地址:https://www.cnblogs.com/Vty66CCFF/p/12235322.html
Copyright © 2011-2022 走看看