简体   繁体   中英

How can I store an array of char in an array in c++

Hi so I'm writing code in C++ that asks the user to submit a message like "the house is green" and then store it an array that stores messages so this is what i have so far

#include <iostream> 

using namespace std;

char message[100];//limits the message to 99 characters.

char arrayOfMessages [5];

cout<<"Please enter the message";

cin>>message; 

I can´t figure out a way to make

arrayOfMessages[0]= message; // since doing this only stores the first position 

Appreciate the help or suggestions if I should do something different in obtaining the message. Also this is an over simplified version but is the gist of what im trying, however im trying to make the array message be temporary so i can reuse it to request up to 5 messages from the user, in my code version I did this with a while cycle.

Use std::vector and std::string :

#include <iostream>
#include <vector>
#include <string> 

int main() {
    //char message[100];//limits the message to 99 characters.
    std::string message; //use std::string instead of char[]
    
    std::vector<std::string> arrayOfMessages;
    arrayOfMessages.reserve(5); //reserve space for 5 strings

    std::cout << "Please enter the message";

//    std::cin >> message; 
    std::getline(std::cin, message); //use this if there's more than one word

    arrayOfMessages.emplace_back(message); // put the message in the array
}
  • std::vector is a dynamic array which can contain elements of any one type. Here we store std::string type in it. It will automatically grow. For example if you have 6 strings, it's size will automatically increase to 6 when you emplace_back another element.
  • std::string is how we do strings in C++. char [] is also possible, but don't use it unless you really have a very good reason to.
  • emplace_back will append the string to the end of the array.

So I found the simplest answer was to simply change the

char arrayOfMessages [5];

to

string arrayOfMessages [5];

and then just do a simple

arrayOfMessages [0]=message;

And that worked, so thanks for everyone's help and suggestions!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM