Triple character in char array..

closed account (E3h7X9L8)
why doesnt it work ? how can i fix it ?

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
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

int main()
{
    char s[50];
    char c;

    cout <<"Char array: "; gets(s);
    cout <<"\nLetter to triple: "; cin >>(c);
    int n = strlen(s);

    for(int i = 0; i != n; i++)
    {
        if(s[i] == c) 
        {
            for(int j = n - 1; j < n; j--) 
            {
                s[j+2] = s[j]; 
            }
            s[i+1] = c;
            s[i+2] = c; 
        }
    }

    cout << s[50];
    return 0;
}
Last edited on
So whats the question?
closed account (E3h7X9L8)
check now
Well I ran it, but what is it your trying to achieve? What is the user supposed to enter when asked:
Char array: ?
Im also not very familiar with the gets() function, but I did do some quick reading and apparently its not a very good function to use.
A better alternative to gets(), is fgets().
Last edited on
A better alternative to gets(), is fgets().

Actually the better alternative would be getline(), this is C++ not C and mixing C-stdio and C++ streams should be avoided.

What is C-stdio anyways?
c-stdio is C's standard input output library.

C++'s "standard input output library" would be iostream
Last edited on
I have not programmed in C, but im assuming implementing c-stdio in this program would be redundant since iostream is what should be used?
Line 21. You are decrementing j but loop ends with j is equal to n. As a result, j goes from n-1 to negative-a-whole-lot until the program crashes.

The first time through the loop the code overwrites the null terminator.

At line 30 you output a single character - one past the last character in s. This is because in C++, defining char s[50] creates an array whose elements are s[0] through s[49].

Can you give an example of the expected output? For example, if the input is "this is a test" and the chacter to triple is 't' then what should the output be?
closed account (E3h7X9L8)
this is a test
ttthis is a tttesttt
Don't do in-place operation. Use a second (larger) array for the result.
Keskiverto is right. The best way to do this is to use std::string, but if you must use a C-string then do it like this:
- go through the input string and compute the size of the output string
allocate the output string
-go back through the input string, copying to the output string. Use two pointers here, one for the source and one for the destination.
- Don't forget to include the null-terminator when you're done.
Topic archived. No new replies allowed.