weird substring error?

hello all, this is my first program in C++
its supposed to find the distance between two coordinates in the form (x,y)
when i substring the 'y' value, it keeps the ')' with it
heres the code... any help would be appreciated

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void main()
{
   string input, num;
   int x1, x2, y1, y2;
   cout << "Enter an (x,y) pair without spaces: ";
   getline(cin,input);

   int start = input.find("(")+1;
   int mid = input.find(",")-1;
   int end = input.find(')')-1;

   num = input.substr(start,mid);
   cout << num << "\n";
   mid += 2;
   num = input.substr(mid,end);
   cout << num << "\n";
   system("pause");
}


why doesn't the '-1' in 'int end' take care of that?
i tried subtracting 2 also, but i got the same result
Last edited on
First of all, int main(), not void main().

Second of all, you need to #include <cstdlib> in order to use system().
(or, better yet, don't use system() - there are better alternatives)

Now, about your problem:
num = input.substr(mid,end);
doesn't give you the substring between positions "mid" and "end".

It gives you the substring starting from position "mid" and with a length of "end" characters, or just from "mid" to the end of the string if there aren't "end" characters between "mid" and the end of the string.
(the reason it worked the first time, was that you probably just got lucky and the numbers happened to have worked out and given you the correct substring)

See http://www.cplusplus.com/reference/string/string/substr/ if that doesn't make sense.

Now do you see your problem?
Last edited on
ahhh okay i see now. the substring in java is different than this. but why do i have to use int main() if im not returning anything? i was planning on just using cout for everything.

and how would you suggest going about this program?
Last edited on
The C++ Standard demands that main() return an int.
See, look!
my compiler wrote:
error: '::main' must return 'int'

(good news for you: it also says you don't have to put a return statement at the end of main()...it'll just be the same as if you had written return 0; at the end)

Here's a hint on the second parameter of substr: To get the number of integers from A to B, it's (B - A + 1).
(for example: number of integers from 6 to 17 = 17 - 6 + 1 = 12)
Last edited on
hmm thats weird. in visual C++ it works with void and without cstdlib.
and that logic hint really did help. i got it to work
Last edited on
Topic archived. No new replies allowed.