Simple string-to-int and int-to-string conversion

Lucaci Andrew 0 Tallied Votes 497 Views Share

Simple conversion between string and int.

#include <iostream>
#include <sstream>
#include <string>
#include <assert.h>
#include <cctype>
using namespace std;

string toStd(int i){
	stringstream toStd;
	toStd<<i;
	return (toStd.str());
}

bool isInt(string s){
	for (int i=0;i<(int)s.size();i++)
		if (isdigit(s[i])==0) return (false);
	return (true);
}

int toInt(string s){
	stringstream toInt;
	int ret;
	if (isInt(s)){
		toInt<<s;
		toInt>>ret;
		return (ret);
	}
	else return (-1);
}

int main(){
	string c="2312", b;
	int i=1123, j;
	assert ((b=toStd(i))=="1123");
	assert ((j=toInt(c))==2312);
	return (0);
}
ravenous 266 Posting Pro in Training

You shoud test your IsInt function with "-1", which is also an int :o)

commented: Notice taken into consideration. +3
Lucaci Andrew 140 Za s|n

Noticed that, working on fixing the bug. 10x ravenous for noticing.

Here, this should patch up quite nice:

bool isInt(string s){
    string dash="-";
    if (s[0]==dash[0]) s.erase(0, 1);
    for (int i=0;i<(int)s.size();i++)
        if (isdigit(s[i])==0) return (false);
    return (true);
}



int main(){
    string s="-2";
    int i=toInt(s);
    assert((i+1)==-1);
    cout<<i+1;
    string s1="-22-2";
    assert (isInt(s1)==false);
    return (0);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.