How to copy a string to an array?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
#include<string>
using namespace std;

int main(){
	
	char char_array[10];
	int ascii_array[10];
	char user_entry = ' ';

	
	strcpy(char_array, "string");

	cin >> user_entry;

	char_array[10] = user_entry;

	cout << char_array;  // prints "Some string data"

	system("pause");
	return 0;
}



Hello I have been trying for a while to copy a string to an array, i know i can copy an char_array element to a string but its with a two dimension. How can i do this? i want it to be user entered. Sorry for my grammatical errors.
You have declared user_entry as a single char (not an array) so it will only contain the first character of the user's input.

 
char_array[10] = user_entry;

This will write to the char user_entry to the 11:th position in the char_array array. char_array only has 10 elements so this is out of bounds.

If you change user_entry to an array you can use strcpy to copy the string, like you do on line 12.

All this is much easier if you use std::string, and you don't have to worry the user input is too large to fit in the array.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
#include<string>
using namespace std;

int main(){
	
	char char_array[1][10];
	int ascii_array[10];
	string user_entry;

	
	

	cin >> user_entry;

	char_array[0] = user_entry;

	cout << char_array[0];  

	system("pause");
	return 0;
}


I want to do something like this, sorry i did not fix the code before,
i want to put a string into an array, so i could then by each of the columns of the 2 dimension array of the element [0][here] see each letter that the user entered.
So then i can convert each letter to int with casting.
Sorry again for my grammatical.
Hey;
Use a vector, you no need to maintain the index for the array.
You need to push the data sequentially to the vector and access it as your own need.

#include "stdafx.h"
#include <iostream>
#include <vector>

int main ()
{
std::vector<char> myvector;
char mychar;

std::cout << "Please enter some chars\n";
int i=0;
do {
std::cin >> mychar;
myvector.push_back (mychar);
i++;
} while (i<10);

std::cout << "myvector stores " << int(myvector.size()) << " chars.\n";
for(int i=0;i<10;i++)
{
std::cout<<myvector[i];
}

return 0;
}

for more details please read
http://www.cplusplus.com/reference/vector/vector/push_back/
Topic archived. No new replies allowed.