pythonchallenge之C++学习篇-02

第二关任然是一个字符处理的关卡

查看网页源码发现有一大串字符需要处理,这么多的字符如果放在源代码里就很不好了

所以要用到C++对文件的操作,用到的头文件是fstream

这里参照了这个博文

对文件处理上来说要对立面的字符串进行字符类型判断,对单个字符类型的判断(比如说属于字母还是数字)要用到一写字符操作函数,这些函数在cctype标准库里面

判断字符是否为字母的函数是isalpha()

好了废话不多说,第二关:

目的:读取文本里面的字符串并处理

解决方案:

 1 # include <iostream>
 2 // # include <math.h>
 3 # include <string>
 4 # include <fstream>
 5 # include <cctype>
 6 
 7 using std::string;
 8 using std::cout;
 9 // using std::cin;
10 // using std::endl;
11 using namespace std;
12 
13 int main()
14 {
15     ifstream infile;//definate fstream
16     string temp; //define a var to store strings
17 
18     infile.open("myfile.txt"); //open the file
19 
20     while (getline(infile, temp)) //use getline() fuction
21     {
22         for (int i = 0; i < temp.size(); ++i)
23         {
24             if (isalpha(temp[i]))
25             {
26                 cout << temp[i] ;
27             }
28         }
29 
30     }
31     return 0;
32 }

遇到的困难和解决方案:

1.读取文件怎么读到里面的每行的字符串而不用多个》》操作符呢,答案是用while循环和getline函数

2.如何判断字符类别呢?答案是用cctype

原文地址:https://www.cnblogs.com/wybert/p/4019687.html