输入2d字符数组时出错

Error in inputting a 2d character array

本文关键字:出错 数组 字符 2d 输入      更新时间:2023-10-16

我正在输入一个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";
}

但是它没有打印任何东西。

有什么问题吗?

这是因为cin忽略空白和换行符('n',其ASCII码为13)。这意味着条件if(a[i][j] == 13)的求值永远不会为真。

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

这可以工作,因为cin.get()方法不会忽略换行符('n')。