Reputation: 87
So I have to write a program that adds a character in array at specific position taking input from user. E.G, the array is {‘A’,‘B’,‘R’,‘L’,‘O’,‘M’,‘C’}, so after inserting "M" at index 2, it should become {‘A’,‘B’,‘M’,‘R’,‘L’,‘O’,‘M’,‘C’}. My problem is that my code overwrites the value at index 2 hence losing it in the process..
Here's the code:
char array[20], insert, temp;
int size = 10, index, count = 0;
cout << "Enter characters : ";
cin >> array;
cout << "Enter a character you want to insert : ";
cin >> insert;
cout << "Enter index you want to insert in : ";
cin >> index;
for (int i = index; array[i] != '\0'; i++)
{
temp = array[index + 1];
array[index] = insert;
}
for (int i = 0; array[i] != '\0'; i++)
{
cout << array[i] << " ";
}
Upvotes: 0
Views: 1360
Reputation: 16454
You shouldn't use C-strings. But more important you shouldn't use C-strings with std::cin because you can't limit the number of characters and your program can cause a buffer overflow.
You should use a dynamic container like std::string. Most containers provide a method like std::string::insert to insert elements at a specific position.
Know your tools (algorithms) and don't reinvent the wheel.
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::size_t;
using std::string;
int main()
{
cout << "Enter characters : ";
string array;
cin >> array;
cout << "Enter a character you want to insert : ";
string insert;
cin >> insert;
cout << "Enter index you want to insert in : ";
size_t index;
cin >> index;
array.insert(index, insert);
for (const auto &c : array) {
cout << c << " ";
}
}
Upvotes: 4