码迷,mamicode.com
首页 > 编程语言 > 详细

C++的简单文本IO

时间:2019-01-11 23:21:11      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:name   filename   span   fail   mes   rds   printf   ann   字符   

从命令行读取一个文件的文件名,输出文本有多少个字符

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int count_words(char *filename){
    int nb_of_chars = 0;
    char ch;
    ifstream inFile;
    inFile.open(filename);
    if(!inFile.is_open()){
        printf("%s cannot open\n", filename);
        exit(EXIT_FAILURE);
    }
    inFile >> noskipws;
    inFile >> ch;
    while(inFile.good()){
        nb_of_chars++;
        inFile >> ch;
    }
    return nb_of_chars;
}
int main(int args, char *argv[]){
    int res;
    res = count_words(argv[1]);
    printf("%s\t%d\n", argv[1], res);
}

要注意的是C++的ifstream创建的inFile会默认跳过空白字符,因此noskipws是一个必要的参数

C++的简单文本IO

标签:name   filename   span   fail   mes   rds   printf   ann   字符   

原文地址:https://www.cnblogs.com/AcodingDg/p/10257652.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!