Problem with strings.

This program compiles with no errors and works fine till line 24, but as I press Enter it pops up a debug error

R6010
- abort() has been called.

Where do you think the problem is?


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
43
44
45
  #include<iostream>
#include<conio.h>
#include<string>
using namespace std;
string encrypt(string boom);
string decrypt(string &boom);


int main()
{
	             
	cout<<"	Press E to encrypt or D to decrypt.\n \
-------------------------------------------------------------------------------\n\n";
string boom; 
char res;

	
		
		res=_getch();
	if(res=='e')
	{
		cout<<"Enter the string to encrypt: "<<endl;
		cin>> boom; // code works fine till here
		
		string en;
int num=0;
for(int i=0; i<boom.length(); i++)

{

	if(int(boom.at(i)%2)==1)
		num=21;
	else
	num=20;
	en.at(i)=int(boom.at(i))+num;

}
		cout<<"Encrypted text is: "<<en<<endl;
	}
	
		return 0;



}
The empty string en is defined at line 25. Then later at line 35 en.at(i) attempts to modify characters of en which are outside the string. That is the cause of the error.
Thanks a lot Chervil. I added this on line 24 string en=boom; and it worked fine. Is there any other way of doing it too?
That's a pretty much ok way to do it.
you could instead do this:
1
2
    string en;
    en.resize(boom.size());

or construct a string with the required length when the string is defined:
string en( boom.size(), ' ');

or this, which constructs the string as a copy of boom:
string en(boom);

As is often the case, there are many different choices.
Just wondering, What's the use of ' ' in string en( boom.size(), ' ');?
Read up on the various string constructors here:
http://www.cplusplus.com/reference/string/string/string/

The example I gave was (6) Fills the string with n consecutive copies of character c.
Topic archived. No new replies allowed.