2D 数组如何允许输入中的空格
2d array how to allow white space in input?
>2d 数组,如何接受输入中的空格? 在 1D 数组中,我认为正确的代码是cin.getline(array,5)
但在 2D 数组中,我无法弄清楚什么是正确的参数。
这是我的代码
#include<iostream>
void display();
char array[2][5];
using namespace std;
int main(){
for (int x = 0; x < 2; ++x) {
for (int y = 0; y < 5; ++y) {
display();
cout << "Enter a value: ";
cin>>array[x][y]; //i want to accept space in input. cin.getline(array[x][y],?)
system("cls");
}
}
display();
}
void display(){
for(int x = 0; x<2; x++){
for(int y = 0; y<5; y++){
cout<<" " <<array[x][y] <<" ";
}
cout<<endl;
}
}
最后,如何限制 cin>> 中的输入? 例如,它只允许 1 个字符的输入。
如何接受输入中的空格?
问题出在你的逻辑上。您试图将string
或char*
简单地存储到字符中。即使它是一个 2D 数组,它也不会那样工作。为此,您需要char*
或std::string
,如下所示。
#include<iostream>
using namespace std;
void display();
string array[2][5];
int main()
{
for (int x = 0; x < 2; ++x)
{
for (int y = 0; y < 5; ++y)
{
display();
cout << "Enter a value for ["<<x+1<<"]["<<y+1<<"]: ";
std::getline(std::cin, array[x][y]);
system("cls");
}
}
display();
}
void display()
{
for(int x = 0; x<2; x++)
{
for(int y = 0; y<5; y++)
cout<<" " <<array[x][y] <<" ";
cout<<endl;
}
}
希望是这种情况,有任何疑问,请问。
#include<iostream>
void display();
char array[2][5];
using namespace std;
int main() {
for (int x = 0; x < 2; ++x) {
for (int y = 0; y < 5; ++y) {
display();
cout << "Enter a value: ";
cin>>array[x][y];
if(array[x][y]==" ";
break;
system("cls");
}
}
display();
}
void display() {
for(int x = 0; x<2; x++) {
for(int y = 0; y<5; y++) {
cout<<" " <<array[x][y] <<" ";
}
cout<<endl;
}
}
相关文章:
- 2D数组来自文本输入,中间有空格
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 如何打印不带空格的输入整数?
- 如何删除已输入的书以及如何使标题,语言和名称在上面放置空格不会出错?
- 当输入在带有空格的单行中给出时,cin 如何在 while 循环中工作?
- 从输入文件修剪空格
- 防止在字符数组中输入双倍空格在 C++
- 如何处理包含空格的 cin 的用户输入?
- C++ - 如何将空格键转换为短划线以进行cmd输入
- CIN不接受C++中带有空格的输入?
- 将空格作为单字符数据类型的输入?
- 防止控制台在通道字符(在 c++ 中)中输入空格(即空格、制表符和换行符)
- 用空格填充 2D 数组(从文件输入)
- 获取由空格分隔的未知大小的单行输入,并将其存储到整数数组中
- 检测要在 if 语句中使用的输入空格
- 如果用户输入两个或多个由空格分隔的字符串C++如何防止缓冲区溢出?
- 使用 Get 的 C++ 输入被替换为空格、不正确的数字
- 在 C++ 中输入带有空格的字符数组
- 仅 C++ 字母和空格输入验证
- 允许用户使用空格输入