0

嗨,我正在用 C++ 编写代码,要求用户提交一条消息,如“房子是绿色的”,然后将其存储为一个存储消息的数组,所以这就是我目前所拥有的

#include <iostream> 

using namespace std;

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

char arrayOfMessages [5];

cout<<"Please enter the message";

cin>>message; 

我想不出办法

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

如果我在获取消息时应该做一些不同的事情,请感谢帮助或建议。这也是一个过度简化的版本,但这是我尝试的要点,但是我试图使数组消息是临时的,所以我可以重用它来向用户请求最多 5 条消息,在我的代码版本中,我用而循环。

4

2 回答 2

4

使用std::vectorstd::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是一个动态数组,可以包含任何一种类型的元素。在这里,我们将std::string类型存储在其中。它会自动增长。例如,如果您有 6 个字符串,当您添加emplace_back另一个元素时,它的大小将自动增加到 6。
  • std::string是我们在 C++ 中处理字符串的方式。char []也是可能的,但除非你真的有充分的理由,否则不要使用它。
  • emplace_back将字符串附加到数组的末尾。
于 2020-07-30T07:40:31.363 回答
0

所以我发现最简单的答案是简单地改变

字符数组消息[5];

字符串数组消息[5];

然后做一个简单的

arrayOfMessages [0]=消息;

这很有效,所以感谢大家的帮助和建议!!

于 2020-07-30T08:59:07.527 回答