473,779 Members | 1,913 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

return from my function is nan

Dear all,

I tried sth easy(actually this was an exercise) but I tried to use the
standard lib. heavily for this problem(as far as I can). There was one
point I could not figure out. The problem is :

../a.out 1.3+3.2+.1+40/3*8/7-4*5-32

The program will parse the argument and find the result of the above
expression. I have two versions(the 2nd is working , not perfect ;-}),
but the first have a return problem I guess because if I use that
version I get "nan" as the result at line 37. What is my problem?

Sorry that there are some comments and cout statement in around the
code. But I guess it could be easier to figure out.

My Best,

1: this version returns nan from the "performer function"
--------------
3 #include <iostream>
4 #include <string>
5 #include <vector>
6 #include <sstream>
7 #include <algorithm>
8 #include <cstdlib>
9 using namespace std;
10
11 template <typename T>
12 T str_To_num (const std::string & s)
13 {
14 T result;
15 std::istringstr eam stream (s);
16 if (stream >result)
17 return result;
18 else{
19 cerr << "error in conversion" <<endl;
20 return EXIT_FAILURE;
21 }
22 }
23 void parse_string(co nst
string&str,vect or<double>&stri ng_num_vec,vect or<char>&operat ors_vec){
24 string str_temp=str;
25 string operators("+-*/");
26 string value;
27 string::size_ty pe index;
28 while((index=st r_temp.find_fir st_of(operators ))!
=string::npos){
29 operators_vec.p ush_back(str_te mp[index]);
30 value=str_temp. substr(0,index) ;
31
string_num_vec. push_back(str_T o_num<double>(v alue));
32 str_temp=str_te mp.substr(index +1);
33
if(str_temp.fin d_first_of(oper ators)==string: :npos)
34
string_num_vec. push_back(str_T o_num<double>(s tr_temp));
35 }
36 }
37 double performer(vecto r<double>&vec_d ,vector<char>&v ec_ch){
38 double result_temp;
39 string md("*/");
40 string pm("+-");
41 vector<char>::i terator iter;
42 vector<int>::si ze_type index;
43
if((iter=find_f irst_of(vec_ch. begin(),vec_ch. end(),md.begin( ),md.end())
)!=vec_ch.end() )
44 ;
45 else
if((iter=find_f irst_of(vec_ch. begin(),vec_ch. end(),pm.begin( ),pm.end())
)!=vec_ch.end() )
46 ;
47 else
48 ;
49 switch (*iter){
50 case '*':
51 index = iter-vec_ch.begin();
52 result_temp=vec _d[index]*vec_d[index+1];
53
vec_d.insert(ve c_d.erase(vec_d .erase(vec_d.be gin()
+index)),result _temp);
54 vec_ch.erase(it er);
55 break;
56 case '/':
57 index = iter-vec_ch.begin();
58 result_temp=vec _d[index]/vec_d[index+1];
59
vec_d.insert(ve c_d.erase(vec_d .erase(vec_d.be gin()
+index)),result _temp);
60 vec_ch.erase(it er);
61 break;
62 case '+':
63 index = iter-vec_ch.begin();
64 result_temp=vec _d[index]+vec_d[index+1];
65
vec_d.insert(ve c_d.erase(vec_d .erase(vec_d.be gin()
+index)),result _temp);
66 vec_ch.erase(it er);
67 break;
68 case '-':
69 index = iter-vec_ch.begin();
70 result_temp=vec _d[index]-vec_d[index+1];
71
vec_d.insert(ve c_d.erase(vec_d .erase(vec_d.be gin()
+index)),result _temp);
72 vec_ch.erase(it er);
73 break;
74 default:
75 ;
76 }
77 if(/*vec_d.size()!= 1*/vec_ch.size()!= 0){
78 for(vector<doub le>::const_iter ator
i=vec_d.begin() ;i!=vec_d.end() ;++i)
79 cout << *i << endl;
80 cout << "------------"<<endl;
81 performer(vec_d ,vec_ch);
82 }
83 else
84 return vec_d[0];
85 }
86 int main(int argc, char *argv[]){
87 if(argc!=2){
88 cout << "Usage error should be: <program_name
<mathematical expression" << endl;
89 cout << "Example: operator 1.3+3.2+.
1+40/3*8/7-4*5-32" << endl;
90 return EXIT_FAILURE;
91 }
92 // convert c-style string argument to a c++ string
93 string arg(argv[1]);
94 //cout << arg << endl;
95 vector<doublenu ms;
96 vector<charops;
97 parse_string(ar g,nums,ops);
98 cout << performer(nums, ops) << endl;
99 return 0;
100}

2: on this version, at the end vector includes only one element that
is the result
-------------------------

1 // C++ way of parsing: heavy use of standard library, string parsing
functions
2 //
=============== =============== =============== =============== ===========
=====
3 #include <iostream>
4 #include <string>
5 #include <vector>
6 #include <sstream>
7 #include <algorithm>
8 #include <cstdlib>
9 using namespace std;
10
11 template <typename T>
12 T str_To_num (const std::string & s)
13 {
14 T result;
15 std::istringstr eam stream (s);
16 if (stream >result)
17 return result;
18 else{
19 cerr << "error in conversion" <<endl;
20 return EXIT_FAILURE;
21 }
22 }
23 void parse_string(co nst
string&str,vect or<double>&stri ng_num_vec,vect or<char>&operat ors_vec){
24 string str_temp=str;
25 string operators("+-*/");
26 string value;
27 string::size_ty pe index;
28 while((index=st r_temp.find_fir st_of(operators ))!
=string::npos){
29 operators_vec.p ush_back(str_te mp[index]);
30 value=str_temp. substr(0,index) ;
31
string_num_vec. push_back(str_T o_num<double>(v alue));
32 str_temp=str_te mp.substr(index +1);
33
if(str_temp.fin d_first_of(oper ators)==string: :npos)
34
string_num_vec. push_back(str_T o_num<double>(s tr_temp));
35 }
36 }
37 void performer(vecto r<double>&vec_d ,vector<char>&v ec_ch){
38 double result_temp;
39 string md("*/");
40 string pm("+-");
41 vector<char>::i terator iter;
42 vector<int>::si ze_type index;
43
if((iter=find_f irst_of(vec_ch. begin(),vec_ch. end(),md.begin( ),md.end())
)!=vec_ch.end() )
44 ;
45 else
if((iter=find_f irst_of(vec_ch. begin(),vec_ch. end(),pm.begin( ),pm.end())
)!=vec_ch.end() )
46 ;
47 else
48 ;
49 switch (*iter){
50 case '*':
51 index = iter-vec_ch.begin();
52 result_temp=vec _d[index]*vec_d[index+1];
53
vec_d.insert(ve c_d.erase(vec_d .erase(vec_d.be gin()
+index)),result _temp);
54 vec_ch.erase(it er);
55 break;
56 case '/':
57 index = iter-vec_ch.begin();
58 result_temp=vec _d[index]/vec_d[index+1];
59
vec_d.insert(ve c_d.erase(vec_d .erase(vec_d.be gin()
+index)),result _temp);
60 vec_ch.erase(it er);
61 break;
62 case '+':
63 index = iter-vec_ch.begin();
64 result_temp=vec _d[index]+vec_d[index+1];
65
vec_d.insert(ve c_d.erase(vec_d .erase(vec_d.be gin()
+index)),result _temp);
66 vec_ch.erase(it er);
67 break;
68 case '-':
69 index = iter-vec_ch.begin();
70 result_temp=vec _d[index]-vec_d[index+1];
71
vec_d.insert(ve c_d.erase(vec_d .erase(vec_d.be gin()
+index)),result _temp);
72 vec_ch.erase(it er);
73 break;
74 default:
75 ;
76 }
77 if(/*vec_d.size()!= 1*/vec_ch.size()!= 0){
78 performer(vec_d ,vec_ch);
79 }
80 //else
81 // return vec_d[0];
82 }
83 int main(int argc, char *argv[]){
84 if(argc!=2){
85 cout << "Usage error should be: <program_name
<mathematical expression" << endl;
86 cout << "Example: operator 1.3+3.2+.
1+40/3*8/7-4*5-32" << endl;
87 return EXIT_FAILURE;
88 }
89 // convert c-style string argument to a c++ string
90 string arg(argv[1]);
91 //cout << arg << endl;
92 vector<doublenu ms;
93 vector<charops;
94 parse_string(ar g,nums,ops);
95 //cout << performer(nums, ops) << endl;
96 performer(nums, ops);
97 for(vector<doub le>::const_iter ator iter=nums.begin ();iter!
=nums.end();++i ter)
98 cout << *iter << endl;
99 //for(vector<char >::const_iterat or iter=ops.begin( );iter!
=ops.end();++it er)
100 // cout << *iter << endl;
101 return 0;
102 }

Jan 28 '07 #1
2 2478
On Sun, 28 Jan 2007 08:28:26 -0800, utab wrote:
Dear all,

I tried sth easy(actually this was an exercise) but I tried to use the
standard lib. heavily for this problem(as far as I can). There was one
point I could not figure out. The problem is :

./a.out 1.3+3.2+.1+40/3*8/7-4*5-32

The program will parse the argument and find the result of the above
expression. I have two versions(the 2nd is working , not perfect ;-}), but
the first have a return problem I guess because if I use that version I
get "nan" as the result at line 37. What is my problem?

Sorry that there are some comments and cout statement in around the code.
But I guess it could be easier to figure out.
ummm....

I was going to suggest that you read the "dragon book" but upon closer
examination consider this. Since you are calling a.out remember that UNIX
shells usually expand '*' characters to wildcards. Quote your expression
then see what happens.
Jan 29 '07 #2
37 double performer(vecto r<double>&vec_d ,vector<char>&v ec_ch){
38 double result_temp;
39 string md("*/");
40 string pm("+-");
41 vector<char>::i terator iter;
42 vector<int>::si ze_type index;
43
if((iter=find_f irst_of(vec_ch. begin(),vec_ch. end(),md.begin( ),md.end())
)!=vec_ch.end() )
44 ;
45 else
if((iter=find_f irst_of(vec_ch. begin(),vec_ch. end(),pm.begin( ),pm.end())
)!=vec_ch.end() )
46 ;
47 else
48 ;
49 switch (*iter){
50 case '*':
51 index = iter-vec_ch.begin();
52 result_temp=vec _d[index]*vec_d[index+1];
53
vec_d.insert(ve c_d.erase(vec_d .erase(vec_d.be gin()
+index)),result _temp);
54 vec_ch.erase(it er);
55 break;
56 case '/':
57 index = iter-vec_ch.begin();
58 result_temp=vec _d[index]/vec_d[index+1];
59
vec_d.insert(ve c_d.erase(vec_d .erase(vec_d.be gin()
+index)),result _temp);
60 vec_ch.erase(it er);
61 break;
62 case '+':
63 index = iter-vec_ch.begin();
64 result_temp=vec _d[index]+vec_d[index+1];
65
vec_d.insert(ve c_d.erase(vec_d .erase(vec_d.be gin()
+index)),result _temp);
66 vec_ch.erase(it er);
67 break;
68 case '-':
69 index = iter-vec_ch.begin();
70 result_temp=vec _d[index]-vec_d[index+1];
71
vec_d.insert(ve c_d.erase(vec_d .erase(vec_d.be gin()
+index)),result _temp);
72 vec_ch.erase(it er);
73 break;
74 default:
75 ;
76 }
77 if(/*vec_d.size()!= 1*/vec_ch.size()!= 0){
78 for(vector<doub le>::const_iter ator
i=vec_d.begin() ;i!=vec_d.end() ;++i)
79 cout << *i << endl;
80 cout << "------------"<<endl;
81 performer(vec_d ,vec_ch);
Here is undefined return value.
82 }
83 else
84 return vec_d[0];
85 }
You should try to compile it with all warnings turned on. Then you
will see, that in function perform is sometimes undefined returned
value, because it simply does not return any value.

Jan 29 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
8270
by: Colin Graham | last post by:
Im working on some asp code using vbscript but i cant seem to get the following code to work. I can get the result from the database but im having to joy returning the value to the html code in order to open a specific document. any help appreciated. I dont get an error message but i get a blank screen. The problem seems to be with the Return Value of the function - i may not be using this correctly. <td>
17
2425
by: strout | last post by:
function F(e) { return function(){P(e)} } Can anybody tell me what the code is doing? If return another function all in a function I would do function F(e)
2
3118
by: Bryan Parkoff | last post by:
I set Function Pointer variable to private so unauthorized users cannot access it, but they are allowed to use Get_ and Set_ functions to modify Function Pointer variable. Look at my example. unsigned char foo(void) { return 0xC1; } unsigned char (*pfoo)(void) = foo;
1
1427
by: XYZ | last post by:
dear group. I have a table with a few columns and I have a form to add/modify/ delete records now whenever a new record is added, i want one column "logged By" to automatically get the windows login name. I found a API function that can do that. but how should I add the return value of the function fOSUserName() to the field in the table.
3
1675
by: poojagupta | last post by:
Hi,I am confused and need the answer of the question mentioned below soon. return(x,y) is valid? Can a return() function return more than one value within one statement. eg: #include<stdio.h> #include<iostream.h> int sum(int i,int j); main() {
2
1307
by: Jeff | last post by:
I had this little bit of code: function parseTemplateData($file){ $file2=preg_replace_callback( "/<edit(.*?)>/s", "parseEditTag", $file); echo $file2;
13
7815
by: Steve | last post by:
On page 392 of "Javascript the definitive guide" a function is called like this:- <form action="processform.cgi" onsubmit="return validateForm();"> Why, in this instance, is the return statement used in calling the function validateForm rather than being included inside the function? Thanks in advance,
7
1893
by: vimal | last post by:
Hi guys, <input class="btn" type="submit" name="terminate" value="Terminate" onclick="return check_proc_sel()" /> i have returned false from check_proc_sel() but still the form's submit event is called It works properly in Firefox but not in IE. solutions???
33
11087
by: zamaam0728 | last post by:
I am at the end of my first semester of C++, and I'm not sure what I should do to make this program meet the requested specifications. The assignment is as follows: Write a function called ignoreCaseCompare() that has two character (char) parameters. The function should return true if the two characters received represent the same letter, even if the case does not agree. Otherwise, the function should return false. Then, write a simple...
0
9474
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10306
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10138
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9930
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8961
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7485
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5373
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5503
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2869
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.