alternative to string. insert with algorithm

this is how i insert character in array of character.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
        char arraytest[10];
 	int position;
	char insert;
		
	cout<<"Enter element to be inserted : ";
	cin>>insert;
		
	cout<<"Position to insert? : ";
	cin>>position;

	int p = position;	

		for(int x=size; x>p; x--)
		{
			array[x]=array[x-1];
		}
	arraytest[p]=insert;


is this possible when im using string? i don't want to use the build in string function like insert or use vectors and i want it like simple algorithms that i used in array characters.
Last edited on
closed account (SECMoG1T)
yes it is possible, also strings are much more dynamic, you don't need to declare the size at all you can just add the character using '+'.

note, in your example above you'll also need to check your bounds.

consider this trivial examples:

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
46
47
48
49
50
51
52
#include<iostream>
#include<string>

using namespace std;


int main()
{
    std::string data, temp("hello");

    for(int i =0; i < temp.size(); i++)
    {
        data += temp[i];
    }

    std::cout<<"result: "<<data<<"\n\n";

    ///---------------------------------------

    string data1;
    const int maxsize = 20;
    char  mychar;

    for(int pos = 0; pos < maxsize; pos++)
    {
        std::cout<<"Enter the character to enter at "<<pos+1<<": ";
        std::cin>>mychar;

        data1 += mychar;
    }

    std::cout<<"\nyou entered "<<data1;

    ///--------------------------------------------

    std::string data2;

    std::cout<<"\n\nEnter a random word: ";
    std::cin>>data2;

    std::cout<<"\nyour input is : "<<data2;

    ///-------------------------------------------
    std::string data3;

    std::cout<<"\n\nEnter a complete sentence: ";
    std::getline(std::cin,data3,'\n');

    std::cout<<"your sentence is: "<<data3;

}
Last edited on
yes, i just noticed about the bounds. thank you for the example.
Hello newguy17,

Yes it is possible. Just replace "array", BTW not a good choice for a variable name, with the name of a string. At its core a "std::string" is an array and it is the string class that handles most of the work for you.

I do question the use of the for loop and wonder if it is inserting properly.

Without more of the code to know what you have I have no way of testing this.

Hope that helps for now,

Andy
closed account (E0p9LyTq)
There are several different ways to add characters and std::strings to a std::string.

operator+
operator+=
append
push_back
insert
replace
http://www.cplusplus.com/reference/string/basic_string/

As with many things C++ there are more ways to do a task, compared to C.

Generating random numbers is another.
Topic archived. No new replies allowed.