输入二维字符数组时出错

时间:2015-09-30 17:21:08

标签: c++ multidimensional-array

我正在输入2D字符数组,当用户点击回车键时必须停止输入。但我的代码没有显示任何输出 输入:

5  // where this is the number of columns, 
   // number of rows are unknown so have taken maximum rows as: 40

数组:

toioynnkpheleaigshareconhtomesnlewx

预期产出:

i = 7, j = 5

这是我的代码:

int main(){
    char a[100][100];
    int n, i, j, p, q;
    cin >> n;
    if(n==0)
       exit(0);

    for(i = 0; i < 40; i++){
        for(j = 0; j < n; j++){
            cin >> a[i][j];

            if(a[i][j]==13)  // 13 = ASCII code for enter key
                goto jump;
        }
    }

jump:
    cout<<i<<"\n"<<j<<"\n";

}

但它没有打印任何东西。

它可能有什么问题?

1 个答案:

答案 0 :(得分:0)

这种情况正在发生,因为cin忽略空格和换行符('\ n',其ASCII码为13)。这意味着条件if(a[i][j] == 13)永远不会评估为真。

解决方案:使用cin.get(a[i][j])代替cin>>a[i][j]

这是有效的,因为cin.get()方法不会忽略换行符('\ n')。