Skip to content

Commit ae066b6

Browse files
Merge pull request kennyledet#487 from ivanchoff/master
string to int functionality in C++
2 parents 2087137 + a1b87c8 commit ae066b6

4 files changed

Lines changed: 57 additions & 0 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
CC= g++ -std=c++11
2+
3+
all: string_to_int
4+
5+
string_to_int: string_to_int.cc
6+
$(CC) string_to_int.cc string_to_int_test.cc -o string_to_int.out
7+
8+
clean:
9+
rm -rf *.out
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#include <sstream>
2+
#include <string>
3+
4+
/*
5+
* Return int from c++ string
6+
*/
7+
8+
int string_to_int(std::string x){
9+
std::stringstream s;
10+
s << x;
11+
int r;
12+
s >> r;
13+
return r;
14+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#ifndef str_to_int
2+
#include <string>
3+
#define str_to_int
4+
5+
/*
6+
* convert c++ string to int
7+
*/
8+
9+
int string_to_int(std::string x);
10+
11+
#endif
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#include<iostream>
2+
#include<cassert>
3+
#include "string_to_int.hpp"
4+
5+
using namespace std;
6+
7+
/*
8+
* Testing with 10 strings
9+
*/
10+
11+
int main(){
12+
//string array for test
13+
std::string str[10] = {"12","99","123","768","892","445123","12389","123456","9871","987654321"};
14+
int sol[10] = {12,99,123,768,892,445123,12389,123456,9871,987654321};
15+
16+
for(int i=0; i<10; ++i){
17+
//check returned value from string_to_int function
18+
assert(string_to_int(str[i]) == sol[i]);
19+
}
20+
cout<<"Tested passed!"<<endl;
21+
return 0;
22+
23+
}

0 commit comments

Comments
 (0)