c++ - 二维数组如何在输入中允许空白?

标签 c++

<分区>

二维数组,如何在输入中接受空格?在一维数组中,我认为正确的代码是 cin.getline(array,5),但在二维数组中,我无法弄清楚什么是正确的参数。

这是我的代码

#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 个字符。提前联系

最佳答案

如何在输入中接受空格?

问题出在你的逻辑上。您试图将 stringchar* 简单地存储到 char。尽管它是一个二维数组,但它不会那样工作。为此,您需要 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;
    }
}

希望是这样,有任何疑问,尽管问。

关于c++ - 二维数组如何在输入中允许空白?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49433336/

相关文章:

c++ - 制作 GUI 时清理 OOP 设计

c++ - 使用 Qt 枚举转换为 qint32

c++ - 使用 C++ 在 Windows 中获取 OSVersion

c++ - 将相机位置传递给着色器 OpenGL

c++ - 智能指针是否能够从容器中删除对其对象的其他引用?

c++ - C++ 中的 WINMAIN 和 main()(扩展)

c++ - 构造函数带参数时如何实例化模板类

c++ - vector.push() 和 vector.reserve() 上的 bad_alloc

c++ - 用于求解具有三对角矩阵的线性方程组的库?

c++ - 如何访问超出范围的变量?