(原創) 写一个字符串相加产生整数的function (C/C++)

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.

1string s = "1236";
2char ca[] = "123";
3// pass these into your AtoiPlus function and output 1359   


Demo code :

 1/* 
 2(C) OOMusou 2006 http://oomusou.cnblogs.com
 3
 4Filename    : AtoiPlus.cpp
 5Compiler    : Visual C++ 8.0
 6Description : 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
18Release     : 11/29/2006
19*/

20#include <iostream>
21#include <string>
22#include <sstream>
23
24int AtoiPlus(const char*const char*);
25
26template <class T> 
27void ConvertFromString(T&const std::string&);
28
29int 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
37template <class T> 
38void ConvertFromString(T& val, const std::string& str) {
39    std::stringstream ss(str);
40    ss >> val;
41}

42
43int 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}

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

posted on 2006-11-29 18:10  真 OO无双  阅读(645)  评论(0编辑  收藏  举报

导航