basic string operation issue

This few lines of code are supposed to extract integers from "it" to "s1", until a '/' is found, however i get a subscript range error, what did i screw up?

1
2
3
4
5
for (i = 0; i < it.find('/'); i++)
	{
		s1[i] = it[i];
	}
	cout << s1;
Can you show more code? Where and how do you define and initialize it and s1? Can you make an example "proof of concept" that demonstrates the problem?

Edit: Perhaps it would be easier for you to use the constructor for std::string meant for substrings.

Four test cases below for you:
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
// Example program
#include <iostream>
#include <string>

int main()
{
    // http://www.cplusplus.com/reference/string/string/string/
    
    {
    std::string input = "first/last";
    std::string output(input, 0, input.find('/'));
    std::cout << output << std::endl;
    std::cout << output.length() << std::endl;
    }
    
    std::cout << "\n";
    
    {
    std::string input = "firstlast";
    std::string output(input, 0, input.find('/'));
    std::cout << output << std::endl;
    std::cout << output.length() << std::endl;
    }
    
    std::cout << "\n";
    
    {
    std::string input = "firstlast/";
    std::string output(input, 0, input.find('/'));
    std::cout << output << std::endl;
    std::cout << output.length() << std::endl;
    }
    
    std::cout << "\n";
    
    {
    std::string input = "/firstlast";
    std::string output(input, 0, input.find('/'));
    std::cout << output << std::endl;
    std::cout << output.length() << std::endl;
    }
}


output:
1
2
3
4
5
6
7
8
9
10
11
first
5

firstlast
9

firstlast
9


0
Last edited on
Sorry for the late update i found a solution already, i needed to use +=
Good to hear, although I do still encourage the use of the std::string constructor instead of manually doing it yourself.

1
2
3
4
5
6
7
8
9
std::string input = "first/last";
std::string output(input, 0, input.find('/'));

// or:

std::string output;
std::string input = "first/last";
// ...
output = std::string(input, 0, input.find('/'));
Topic archived. No new replies allowed.