2D 数组如何允许输入中的空格

2d array how to allow white space in input?

本文关键字:空格 输入 何允许 数组 2D      更新时间:2023-10-16

>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 个字符的输入。

如何接受输入中的空格?

问题出在你的逻辑上。您试图将stringchar*简单地存储到字符中。即使它是一个 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;
    }
}