+= question

Hello,

How come when I enter a name, for example, joey, the output is 1329? How is that even happening? I wouldn't expect the team += a[i] to give me an output like that. Thanks for taking the time to read.

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

int main() {
    string team = "";
    string a = "Billy";
    
    cout << "Enter name: ";
    cin >> team;
    
    for(int i = 0; i < team.size(); i++) {
        if(team.find(a[i]) > a.size()) team += a[i];
        
    }
    cout << team.size() << endl;
    
    return 0;
}
You are not printing the string. You are printing the size of the string.
Yeah, I'm aware of that but how's the size of the string 1329?
I get 51 when I enter Joey.
How is it 51? I don't understand the concept behind it.
This is strange. I presume the if(team.find(a[i]) > a.size()) statement is to check if the character wasn't found. I changed it to if(team.find(a[i]) == string::npos) which is the normal way of checking if it wasn't found, and then if I enter "joey", it prints 8.
There is no range-checking in a[i], as i increases it may easily go beyond the bounds and start accessing extraneous characters from some adjacent memory locations. Meanwhile, team is getting larger and the for loop will find its upper limit increased accordingly.
I wonder that someone gets a number at all. When I enter joey it crashes with "String subscript out of range" when i == 5. Here is the code with some TRACE output.

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
#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdarg.h>

#define TRACE(...) { printf(__VA_ARGS__); }

using namespace std;

int main()
{

    string team = "";
    string a = "Billy";
    
    cout << "Enter name: ";
    cin >> team;
    
    for(size_t i = 0; i < team.size(); i++) 
    {
      TRACE("\nTeam = %s, Team.size = %u", team.c_str(), team.size());
      TRACE("\ni = %u", i);
      streampos pos = team.find(a[i]);
      TRACE("\nTeam = %s", team.c_str()); 
      TRACE("\npos = %u", pos);
      TRACE("\na.size = %u", a.size());
      if(pos > a.size()) 
        team += a[i];
       
    }
    cout << team.size() << endl;
  system("pause");
  
    
    
}
¿what is so hard to understand about undefined behaviour?
Topic archived. No new replies allowed.