while (x!='<letter>') does not work, does with number

solved: || should be &&.

I'm making a dieroller. I take the input in as a string, for example 1d1.
The first while loop finds the number before d, second the number after d.
I don't know why, but 'd' causes it to loop with 1d1, but with '2' and 121 as input it does not. What's wrong here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  void rollxdy()
{
    cout << "Roll: ";
    string input, x, y;
    cin >> input;
    int i=0, j=0;
    while (input[i]!='d' || input[i]!='D')
    {
        x[i]=input[i];
        i++;
    }
    i++;
    while (input[i]!='\n')
    {
        y[j]=input[i];
        i++;
        j++;
    }
}


Also, I was thinking that the second loop stops at "\n", but I'm not sure that is going to work, and can't test it yet.
Last edited on
You are using operator[] on a string that is out of of bounds (both x and y are empty). Hacky solution:

1
2
3
4
5
6
7
8
9
  void rollxdy()
{
    cout << "Roll: ";
    string input, x, y;
    cin >> input;
//assert(input.size() == 3);
    int i= input[0]-'0', j= input[2]-'0';
    
}
Last edited on
Hey elohssa,

That did not work, it is now stuck in the first while loop, regardless of input.

I've figured out that changing || to && fixes it, although i do not understand why. With input[i]!='d', should result in false when it is d. And I think false || true and false && true both result in the while loop being false.

This is the code so far, which functions with any input being <number>d/D<number>..
I don't know what would be a good way to stop the second loop with <number>d/D<number. (So without the dot).

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
void rollxdy()
{
    cout << "Roll: ";
    string input, x_str, y_str;
    cin >> input;
    int i=0, j=0;
    while (input[i]!='d' && input[i]!='D')
    {
        x_str[i]=input[i];
        i++;
       // cout << "In the first loop. ";
    }
   // cout << "Out of the first loop. ";
    i++;
    while (input[i]!='.')
    {
       // cout << "In the second loop. ";
        y_str[j]=input[i];
        i++;
        j++;
    }
    int x=stoi(x_str);
    int y=stoi(y_str);
    cout << x<< y;
}
x_str[i] = ...

This is the same problem as elo mentioned. When i=0 , this is:

x_str[0] = ...
but x_str[0] does not exist. When you create a new string ( string x_str; ) it has size zero. If you want to add char to the end of a string, you can use push_back.

x_str.push_back(input[i])
This will resize the string to make it big enough for the new char, and put the new char in at the end.

Tell me, what happens if tyhe user enters 123 ? With no 'd' in it. When will the loop end? Never. So protect against that.
Registered users can post here. Sign in or register to post.