c ++ 2D数组错误

时间:2016-04-30 19:03:05

标签: c++ arrays

我有一个数组程序,它将根据用户输入读出colunm。如果数组中有空字段,它会以某种方式给我一个错误。例如,如果我在单词helloworl中读到,我的程序将起作用。但是如果我在helloword中读到,我的程序将不会打印最后一个字符,即d。我花了几天时间试图找出如何解决,我希望有人可以帮助我。谢谢。

输出应该是hlodworlwl。现在它显示像这个hloworlwl错过了最后一行。

还有一件事,我的程序将接受用户输入并排序并打印出阵列。我怎么能错误证明程序,以确保用户输入(逻辑上)像123 321 213等而不是111 222 134?

如果我在helloworld中读到并且用户输入123,那么我的2d数组应该是

hel
low
orl
d

输出应该是hlodworlwl。现在它显示像这个hloworlwl错过了最后一行。

还有一件事,我的程序将接受用户输入并排序并打印出阵列。我怎么能错误证明程序,以确保用户输入(逻辑上)像123 321 213等而不是111 222 134?

hel
low
orl
#include <iostream>
#include <string>
using namespace std;

char array[5][5];

//function that prints the column c of the array
void printArray(int c) 
{
   for(int i=0; i<3; i++) 
   {
       cout << array[i][c];
   }
}

int main() {

string alphabate;
string a="helloworld";

for(int i=0; i<3; i++) 
{
    for(int j=0; j<3; j++) 
    {
        array[i][j] = a[j+ (i * 3)];
    }
}

cout << "Enter some alphabate:";
cin >> alphabate;

//checking the input parameters
for (int j=0; j<3; j++) {
    if (alphabate[j] == '1' || alphabate[j] == 'a') 
    {
        printArray(0);
    }
    else if (alphabate[j] == '2' || alphabate[j] == 'b') 
    {
        printArray(1);
    }
    else if (alphabate[j] == '3' || alphabate[j] == 'c') 
    {
        printArray(2);
    }

}

return 0;
}

再次感谢您阅读我的问题。

1 个答案:

答案 0 :(得分:1)

答案很简单&#34; helloworld&#34;有10个字符。您的数组仅存储9. D永远不会在数组中输出。