Very weird problem about string.

Hello ,

I wrote this code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>
#include <string>


using namespace std;


int main()
{
    string str="HelloWorld\n32/78\n34/2\n32/2\n32/2\n~~";
    int end=str.find("\n");
    str.erase(str.begin() , str.begin()+end+1);
    string s2=str.substr(str.find(str.at(0)) , str.find("/"));
    cout<<s2<<"\n";
    string s3=str.substr(str.find("/")+1 , str.find("\n")-1);
    cout<<s3;
    return 0;
}


first , I delete "HelloWorld" from the string.

than , I find the first number before the first "/" (32)
and than I find the second number after the first "/" (78)

but from some reason the output is

32
78
3

(s2 contains the string "32" , and s3 contains the string "78\n3")

and Its weird , the output should be
32
78

because , when I am writing this

string s3=str.substr(str.find("/")+1 , str.find("\n")-1);

it supposed to give me a string that start from the first character after the first slash , and over in the character the comes before the first "\n"

so it adds to s3 "\n" and 3 ?
s3 should contain only 78....

Big thanks for the helpers.
Last edited on
The second argument is supposed to be length, not position.
http://www.cplusplus.com/reference/string/string/substr.html

Personally, I can never remember all these little details very well, so I always keep a reference handy to make sure I get them right.

Hope this helps.
Why don't you write some different separators between inputs (not \n) ?
thanks a lot duoas , I understand it now...

I did like that in it worked

1
2
int bla=str.find("/")+1;
    string s3=str.substr(bla , str.find("\n")-bla);


thanks!
Last edited on
Topic archived. No new replies allowed.