insert character into char array (without using pointer)

closed account (EwCiz8AR)
i've to add character into char array please help me out to solve this program it won,t work :( please someone help me please
example:
Enter the string : I wont be here.

Enter a character: '

Enter position : 6

output:
I won't be here

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
#include <iostream>
#include <string>
using namespace std;

int main()
{
char sentence[100], chtr;
int c=0, pos;
cout << "Enter a sentence: ";
cin.getline(sentence,100);

cout << endl;
cout << "Enter position :";
cin >> pos;
cout << "Enter character :";
cin >> chtr;
int len = strlen(sentence);
if (pos > len)
   pos = len - 1;
if ( (pos > 0) )
{
   for (int m = len; m > pos - 1; m--)
   {
      sentence[m] = sentence[m - 1];
   
   sentence[m] = 0; }  
   sentence[pos - 1] = chtr;
}
cout<<sentence;
}
Last edited on
closed account (Dy7SLyTq)
why not just use std::string?
closed account (EwCiz8AR)
I have no info about std::string :( :( n its my lab task and submit 2moro..
First of all, here's your code with some better indentation:
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
#include <iostream>
#include <string>
using namespace std;

int main()
{
    char sentence[100], chtr;
    int c=0, pos;
    cout << "Enter a sentence: ";
    cin.getline(sentence,100);

    cout << endl;
    cout << "Enter position :";
    cin >> pos;
    cout << "Enter character :";
    cin >> chtr;
    int len = strlen(sentence);
    if (pos > len)
        pos = len - 1;
    if ( (pos > 0) )
    {
        for (int m = len; m > pos - 1; m--)
        {
            sentence[m] = sentence[m - 1];

            sentence[m] = 0;
        }
        sentence[pos - 1] = chtr;
    }
    cout<<sentence;

As you can see, you're missing your closing brace for your main function.
Also, I suspect your problem is that on line 24, you copy the value of sentence[m - 1] to sentence[m] (okay), and then immediately, on line 26, you overwrite sentence[m] with 0, which completely defeats the purpose of having line 24 in there at all.
I suspect you probably meant sentence[m - 1] = 0; on that line instead.

Also, a couple more things:
-- Since the first iteration of your loop essentially does sentence[len] = sentence[len - 1];, and sentence[len] was originally the null character signaling the end of the string, you should probably also do
sentence[len + 1] = '\0';
somewhere in your code (either before or after your loop).

-- You should probably also check to make sure that len < 100, since if len == 100, then you don't have any more room to insert another character.
closed account (EwCiz8AR)
@long double main Thank you soooo much :)
Topic archived. No new replies allowed.