c++ - 如何将数组传递给函数,以便用户可以随意订购“短语”/数组
问题描述
cout << "Now, you will enter four phrases. It does not matter what order you input your phrases, we will sort them for you after you are finished typing your phrases. Your phrases cannot be more than 130 characters long."
<< "Enter your phrase now: ";
cout << endl << endl;
cin.get (phrase_1, max_length);
cin.ignore (130, '\n');
phrase_1[0] = toupper (phrase_1[0]);
cout << "You entered, " << endl << phrase_1;
cout << endl << endl;
所以这允许用户输入他们的短语,不超过 max_length(130,设置为常数)。我的问题是我会像这样遍历每个短语。我需要能够使用函数来大写,寻找额外的空间。不仅如此,我觉得让用户以他们认为的任何方式排列它们,我还需要使用一个函数。
对于下一个短语,我这样做:
cin.get (phrase_2, max_length);
cin.ignore (130, '\n');
phrase_2[0]= toupper (phrase_2[0]);
cout << "You entered, " << endl << phrase_2;
cout << endl << endl;
cout << "Now enter, your next phrase.";
然后我想我可以做到
two = phrase_2; // This will store the phrase so that later we can
这样每个短语都可以用 int 或 char 存储。然后我会让用户输入 1 为 1,2 为 2,3 为 3,4 为 4,他们可以选择顺序。好吧,事实证明这在 c++ 中是不允许的。您不能将 char 数组存储到 char 变量中。
解决方案
所以,要在 C++ 中传递一个数组,你可以这样做:
void toupper(char myarray[]) {
// ...
}
我不确定您的toupper()
函数到底是什么样的,但它可能看起来与此类似。但是,该函数是无效的,您可能希望通过引用传递。或者你也可以返回一个数组,我想。
无论如何,关键是,当你调用它时,它看起来像这样(假设你所有的“短语”都是 char 数组):
toupper(phrase_2);
不需要下标符号([]
括号)。
推荐阅读
- javascript - undefined 不是函数(在'...state.map...'附近)
- kubernetes - 如何调试或分析 Kubernetes RBAC 规则动词和 Api Groups
- python - Python中的BeautifulSoup链接属性
- python - 训练损失改善但验证早期收敛
- ethereum - 在以太坊中,分配地址时,会抛出解析错误
- mysql - 如何查找现在 5 分钟内的日期()
- linux - SSH 连接要求输入密码连接到 Docker 容器
- r - 将嵌套数据整理到数据框:不同类型的嵌套数据 - 逻辑列表和命名列表
- flutter - 将 Text 小部件添加到其子项映射到 Flutter 的 ListView?
- python - 在 Python 中使用十进制模块时如何抑制指数格式