As part of learning c++, rather than using std::string, i want to use char to store and display words. so I wrote a simple program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int max = 10;
std::vector<char> vec;
for(int i=0;i<3;i++){
char ch[max];
std::cout<<"Enter your favorite color:";
std::cin.getline(ch,max);
vec.push_back(ch[max]);
std::cout<< ch <<"\n";
std::cout<< vec[i] <<"\n";
}
I am able to get the user input data and display it, but seem to have problem with storing the data in a vector and displaying the vector data within the same FOR loop. Rather than use iterators to display the vector data in a different FOR loop, i wanted to see if I could display the data within the same loop.
From what I read online, i have a feeling this might not be working due to std::vector<char> vec being neither assignable or copyable. Is that right ? or if I am mistaken, what is causing this problem and how can i use char to store words in a vector and display them within the same FOR loop?
@gunnerfunner I understand the best practices idea. but i don't think it is impossible to use char and store data. I just want to be able to accomplish this. This will help me understand the limitations of each concept. and helps me understand the 'whys' about each command.
@coder777 I want to implement a program using char,vector and 'words' (rather than individual letters).
My basic premise: The user is prompted for a word. The word is input into a char variable and stored in a vector.
I set out on this idea. If you think my example of a program is wrong. Could you help me come up with a simple program where I can implement all the three concepts.
If you think I'm being adamant, I hope you'll see that I'm doing this just to understand limitations of concepts and ideas.
I've done the program with std::string. I got curious with the char option. i believe to get to where you are, I need to try different ways of implementing stuff rather do stuff just one way. Hence this idea.
And thank you for approach. This is closer to what I wanted to do. I just have to rack my brains to come up with different ideas to learn more.
To organize words just with vectors you may use vector of vectors:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int max = 10;
std::vector<std::vector<char> > vec; // The inner vector is the word.
for(int i=0;i<3;i++){
vec.emplace_back(max); // This creates an instance of the inner vector with 'max' char
std::cout<<"Enter your favorite color:";
std::cin.getline(vec.back().data(),max); // This gets the data of the previously created vector
vec.push_back(ch[max]); // This is not needed
std::cout<< ch <<"\n";
std::cout<< vec[i].data() <<"\n"; // Accessing the data of the inner vector which contains the c-string
}