字符串分解

 

关键词:strtok(),atoi()

 

对于一些变态的输入:

  输入 n 个数,输入的格式为每两个数间有',';

  例如:

  input:

  n=10

  1,2,3,4,5,6,7,8,9,10

  你可能只需要数字,而不需要',',那么,该如何从中分解出数字呢?

1.下面介绍strtok()函数:

  

2.字符串与数字间的相互转化函数

  

 1 void Test()
 2 {
 3     //假设输入 n 个数,每两个数间都会有','隔开
 4     //例如 n = 10 "1,2,3,4,5,6,7,8,9,10"
 5 
 6     int n=10;
 7     int num[15];
 8     strcpy(buf,"1,2,3,4,5,6,7,8,9,10\0");
 9 
10     p=strtok(buf,",");
11     num[1]=atoi(p);
12     for(int i=2;i <= n;++i)
13     {
14         p=strtok(NULL,",");
15         num[i]=atoi(p);
16     }
17     for(int i=1;i <= n;++i)
18         printf("%d ",num[i]);
19     printf("\n");
20 }
View Code

 

当时学这个知识点并不是因为在做算法题碰到这种读入的;

而是在学c++面向对象时做的一道题,当时这道题的难点就在于读入;

实现一个学生信息处理程序,计算一个学生的四年平均成绩。
要求实现一个代表学生的类,并且类中所有成员变量都是私有的。

输入
输入数据为一行,包括:
姓名,年龄,学号,第一学年平均成绩,第二学年平均成绩,第三学年平均成绩,第四学年平均成绩。
其中姓名为由字母和空格组成的字符串(输入保证姓名不超过20个字符,并且空格不会出现在字符串两端),年龄、学号和学年平均成绩均为非负整数。信息之间用逗号隔开。

输出
输出一行数据,包括:
姓名,年龄,学号,四年平均成绩。
信息之间用逗号隔开。
View Code
样例输入:
Tom Hanks,18,2017001,80,80,90,70

样例输出:
Tom Hanks,18,2017001,80
样例输入输出

 

参考代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstdlib>
 4 #include<cstring>
 5 using namespace std;
 6 
 7 /**
 8     strtok头文件<cstring>
 9     atoi头文件<cstdlib>
10 */
11 class Student
12 {
13 private:
14     char name[22];
15     int age;
16     char id[22];
17     double average[4];
18 public:
19     void ReadInfo();
20     void Print();
21 };
22 void Student::ReadInfo()
23 {
24     char buf[210];
25     cin.getline(buf,200);//读取一行字符,最多200个
26     
27     char *p=strtok(buf,",");//取第一个逗号前的字符
28     strcpy(name,p);//拷贝给姓名
29     
30     //将第一个','前的字符串变为"NULL",并将第一个和第二个','之间的字符串赋给p;
31     p=strtok(NULL,",");
32     age=atoi(p);//字符串转化为整数
33     
34     //将第一个和第二个','之间的字符串变为"NULL",并将第二个和第三个','之间的字符串赋给p;
35     p=strtok(NULL,","); 
36     strcpy(id,p);
37     for(int i=0;i<4;i++)
38     {
39         p=strtok(NULL,",");//同理
40         average[i]=atof(p);
41     }
42 }
43 void Student::Print()
44 {
45     cout<<name<<','<<age<<','<<id<<',';
46     double total=0;
47     for(int i=0;i<4;i++)
48         total+=average[i];
49     cout<<total/4<<endl;
50 }
51 int main()
52 {
53     Student s;
54     s.ReadInfo();
55     s.Print();
56     return 0;
57 }
View Code

 

posted @ 2019-05-06 12:21  HHHyacinth  阅读(187)  评论(0编辑  收藏  举报