C++的簡單文字IO
阿新 • • 發佈:2019-01-11
從命令列讀取一個檔案的檔名,輸出文字有多少個字元
#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是一個必要的引數