c++ problem

hello, well am a little confused here and I need help to un-stuck my brain :P ::::

1
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
55
56
57
58
59
60
61
//============================================================================
// Name        : quiz3.cpp
// Author      : Ploutarchos 
// Version     :
// Copyright   : Your copyright notice
// Description : Quiz 3rd C++, Ansi-style
//============================================================================

#include <iostream>
#include <cstring>
#include <cstdlib>


using namespace std;
template <class T>
T power(T n, int r){
	T result;
	if(r==0)
		return 1;
	else
	result=n* power(n,r-1);
	return result;
}
bool convertToint(const char *str1, int&);
int main() {
	int n,r;
	int size, Num;
	bool IsNum ;
	//question1
	cout << "pls give me 2 numbers: " << endl;
	cin >> n >> r;
	cout<<"the result of "<<n<<" power to "<< r <<" is: " << power(n,r) << endl;
	//question2
	cout <<"pls give the size of the string: "<< endl;
	cin>> size;
	cin.ignore();
	char* str1 = new char[size+1];
	cout <<"pls give the string that you want to convert: "<<endl;

	cin.getline(str1,size,'\n');
	IsNum=convertToint(str1, Num);

	if(IsNum)
		cout<<"the string that you gave me is a number: "<< Num<<endl;
	else
		cout<<"the string that you gave me is not a number: "<< endl;

	return 0;
}
bool convertToint(const char *str1, int&Num){
	int i=0;
	while(str1[i]!='\0'){

		if(isdigit(str1[i])==0)
			return false;
		i++;
	}
	Num= atoi(str1);
	return true;

}  


my serious problem is on bool convertToint(const char *str1, int&);
that return the values something is going wrong an I can find it
your code:
if(isdigit(str1[i])==0)
is same as:
if(true == false) //false
OR
if(false == false)//true
this is probably not what you expected.
and will program do in this case if it's false.
--if true return false.
--if false return ture-- skip to return true.

try separating them into two if's.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool convertToint(const char *str1, int&Num)
{
	int i=0;
	while(str1[i]!='\0')
	{

		if(! isdigit( str1[i] ))
			return false;
		i++;
	}
	Num = atoi(str1);
	return true;

}  
Last edited on
Topic archived. No new replies allowed.