2013-10-28 117 views
1

我刚刚学习数组,我的书几乎没有解释如何输入二维字符串数组。下面是我的书推荐码:输入多个字符串数组

char lastName[6][50]; 

for(int i = 0; i < 5; i++) 
{ 
    cout << "Enter candidates last name: "; 
    cin.get(lastName[i], 50); 
    cout << endl; 
} 


for(int j = 0; j < 5; j++) 
{ 
    cout << lastName[i] << endl; 
} 

与此代码我只能输入一个名称和节目的其余部分只是重复“输入考生的名字:”

,我试过其他的代码是:

for(int i = 0; i < 5; i++) 
{ 
cout << "Enter candidates last name: "; 
cin >> lastName[i][50]; 
cin.get(lastName[i], 50); 
cout << endl; 
} 

Same output code 

此代码让我输入正确数量的名称,但缺少每个名称的第一个字符。示例“乔”给我“oe”

再次,我是一个初学者,我不明白为什么它不能正常工作。谢谢!

+0

应该'j',而不是'i'在该行'的cout << lastName的[I] << ENDL;' –

回答

1

问题出在混合cingetline。格式化的输入(使用>>运算符)和无格式的输入(getline就是一个例子)不能很好地协同工作。你一定要读更多关于它。 Click here for more explanation

这是您的问题的解决方案。 cin.ignore(1024, '\n');是关键。

char lastName[6][50]; 
for(int i = 0; i < 5; i++) 
{ 
    cout << "Enter candidates last name: "; 
    cin.get(lastName[i], 50); 
    cin.ignore(1024, '\n'); 
} 
for(int j = 0; j < 5; j++) 
{ 
    cout << lastName[j] << endl; 
} 
+0

谢谢!我实际上是在玩它,并做了cin >> lastName,它工作得很好 –