Homework 6 & Midterm 1
Write a function int AtoiPlus(const char*, const char*) that takes two C-style strings containing int digit and return the corresponding int. For example, AtoiPlus("123", "4") return 127. You should write a main routine to test your function. Use at least the following code fragment to test your code.
1
string
s
=
"
1236
"
;
2
char
ca[]
=
"
123
"
;
3
//
pass these into your AtoiPlus function and output 1359

2

3

Demo code :
1
/**/
/*
2
(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4
Filename : AtoiPlus.cpp
5
Compiler : Visual C++ 8.0
6
Description : Homework 6 & Midterm 1
7
Write a function int AtoiPlus(const char*, const char*)
8
that takes two C-style strings containing int digit and
9
return the corresponding int. For example,
10
AtoiPlus("123", "4") return 127. You should write a main
11
routine to test your function. Use at least the following
12
code fragment to test your code.
13
14
string s = "1236";
15
char ca[] = "123";
16
// pass these into your AtoiPlus function and output 1359
17
18
Release : 11/29/2006
19
*/
20
#include
<
iostream
>
21
#include
<
string
>
22
#include
<
sstream
>
23
24
int
AtoiPlus(
const
char
*
,
const
char
*
);
25
26
template
<
class
T
>
27
void
ConvertFromString(T
&
,
const
std::
string
&
);
28
29
int
main()
{
30
std::string s = "1236";
31
char ca[] = "123";
32
int result = AtoiPlus(s.c_str(),ca);
33
34
std::cout << result << std::endl;
35
}
36
37
template
<
class
T
>
38
void
ConvertFromString(T
&
val,
const
std::
string
&
str)
{
39
std::stringstream ss(str);
40
ss >> val;
41
}
42
43
int
AtoiPlus(
const
char
*
s1,
const
char
*
s2)
{
44
std::string str1 = s1;
45
std::string str2 = s2;
46
47
int i = 0;
48
ConvertFromString(i, str1);
49
50
int j = 0;
51
ConvertFromString(j, str2);
52
53
return i + j;
54
}


2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29



30

31

32

33

34

35

36

37

38



39

40

41

42

43



44

45

46

47

48

49

50

51

52

53

54

See Also
(原創)如何将std::string转int,double? (C/C++)
(原創)如何将int,double转std::string? (C/C++)