首页 > 编程语言 > 详细

C++的简单文本IO

时间:2019-01-11 22:34:37      阅读:164      评论:0      收藏:0      [点我收藏+]

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

#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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!