Alright. I'm currently making a login screen for my game. I'm using the library of Allegro 4.2.3. I'm making some textboxes(for the username + password), and receiving input from them with the following function.
#include <string>
usingnamespace std;
#include <allegro.h>
#include "textbox.h"
void TextboxInput(Textbox&t, int&caret, string::iterator&iter, bool&insert) {
string edittext = t.txt;
while(keypressed()) {
int newkey = readkey();
char ASCII = newkey & 0xff;
char scancode = newkey >> 8;
// a character key was pressed; add it to the string
if(ASCII >= 32 && ASCII <= 126) {
// add the new char, inserting or replacing as need be
if(insert || iter == edittext.end())
iter = edittext.insert(iter, ASCII);
else
edittext.replace(caret, 1, 1, ASCII);
// increment both the caret and the iterator
caret++;
iter++;
}
// some other, "special" key was pressed; handle it here
elseswitch(scancode) {
case KEY_DEL:
if(iter != edittext.end()) iter = edittext.erase(iter);
break;
case KEY_BACKSPACE:
if(iter != edittext.begin()) {
caret--;
iter--;
iter = edittext.erase(iter);
}
break;
case KEY_RIGHT:
if(iter != edittext.end()) caret++, iter++;
break;
case KEY_LEFT:
if(iter != edittext.begin()) caret--, iter--;
break;
case KEY_INSERT:
insert = !insert;
break;
default:
break;
}
}
t.txt = edittext;
}
The function above is basically consisting of some copy + pasted code from a tutorial I found. I'm using the exact code from it. Strangely enough, I've used the same exact code in the past; it worked fine. Now, I receive a program crash at the line: iter = edittext.insert(iter, ASCII); after I have typed one character into the string. I have no idea why it's happening. Any help would be appreciated. If you need more details, please let me know - I know I'm bad at explaining things, heh.
Thanks for the reply! I can see why the iterator would have something to do with it, for only string.insert() and string.erase() crash the program, while replace() works fine. How exactly would I fix this? I'm not familiar with string iterators as much as I should be, and I'm pretty clueless about what makes an iterator valid or not.