Variable length input to char array?

*std::string is not an option*

How do I allow the user to pass input to an array of characters where the length of that input can vary?

I have something like this.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
	char a[12];
        for (int i = 0; i < 12; i++) {
		cin >> a[i];
	}
        return 0;
}


however this requires that the user provide 12 characters before it will continue on with the program. i want it to be so that if the user enters three characters, it will assign those 3 characters to the first three elements in the array and then move on with the program.

as a bonus that would be ideal but not necessary is if there was a way to set the length of the array to the total number of characters input.

thanks to everyone who takes a look!
Last edited on
You should use std::vector. New elements can be added dynamically.

Ofcourse, you will still need a way to terminate the for loop, maybe by first reading the length of the input.
vector is also not an option. i need to make the memory that is holding this information thread safe and i cant do std::atomic<std::vector>. i could take the input and hold it in a vector temporarily and then transfer it over to a char array with

for (int i = 0; i < vector.size(); ++i) {}

or something similar with string and ill do that if no one else has any suggestions but im still really interested if there is a more direct way to do this.
Last edited on
closed account (D80DSL3A)
no reply
Last edited on
ok im sorry if this is not what you were asking but here is a messed up code.
new to c++, but i know some of this not good coding practice for sure, but might spring up an idea. hope it helps,
1
2
3
4
5
6
7
8
9
10
11
	string strOne;
	cin >> strOne;
	string::size_type count = strOne.size();
	char *x = new char[count](); 
	for (int i = 0; i < count; i++){
		x[i] = strOne.at(i);
	}
	for (int i = 0; i < count; i++){
		cout << x[i];
	}
	
Last edited on
Topic archived. No new replies allowed.