c++ - 程序异常输出

标签 c++

我有一个程序应该打印出 2 个列表,如下所示,基本上是相同的列表,但倒退了,但是它第一次工作但随后它打印了一些奇怪的输出,我也会在下面显示。

0123456789
9876543210

但是我从程序中得到的实际输出是这样的:

sample Output

谁能告诉我我的代码有什么问题,我不确定为什么会得到这个输出。

void createFile(){
  ofstream myfile;
  myfile.open ("TEST1.txt");
  for(int x = 0; x < 10; x++){
   myfile << x << "\n";
  }
  myfile.close();
}

void popArray(int array1[]){
  ifstream infile("TEST1.txt");

  int x;
  while(infile >> array1[x]){
    cout << array1[x];
  }

}

void reverseList(int array2[]){
  for(int x = 9; x > -1; x--){
    cout << setw(2) << array2[x];
  }
} 

void checkLists(int array1[], int array2[], int sizeOfArray){
  for(int x = array1[1]; x < sizeOfArray; x++){
    for(int y = array2[1]; x < sizeOfArray; x++){
        if(x == y)
            cout << "Palindrome" << endl;
        else{
            cout << "Not" << endl;
        }
    }
  }

} 


int main()
{
  int array1[10];
  int array2[10];

  createFile();
  popArray(array1);

  cout << "\n";

  reverseList(array1);

  cout << "\n";
  checkLists(array1, array2, 10);
}

最佳答案

这是我认为的问题:

void popArray(int array1[]){
 ifstream infile("TEST1.txt");

 int x;
 while(infile >> array1[x]){
 cout << array1[x];
 }

}

您永远不会指定 x 是什么。如果我明白你想做什么,我认为这应该可行:

void popArray(int array1[]){
 ifstream infile("TEST1.txt");

 int x;
 for (x=0; x < 10; x++){
  cout << array1[x];
 }

}

多读一点。你在这里也有错误:

void checkLists(int array1[], int array2[], int sizeOfArray){
 for(int x = array1[1]; x < sizeOfArray; x++){
 for(int y = array2[1]; x < sizeOfArray; x++){
     if(x == y)
        cout << "Palindrome" << endl;
     else{
        cout << "Not" << endl;
    }
    }
   }

}

我会做类似的事情:

bool checkLists(int array1[], int array2[], int sizeOfArray){

bool isPalindrome=true;
for(int x = 0; x < sizeOfArray; x++){

    if(array1[x] != array2[sizeOfArray-(x+1)]){
        isPalindrome = false;
        }
 }

return isPalindrome;
}  

然后在 main 的末尾你可以:

if(checkLists(array1, array2, 10)){
 cout << "Is Palindrome\n";
}
else{
cout << "Is Not Palindrome\n";
}

虽然我在做这件事,但我也可以解决这个问题:

void reverseList(int array2[]){
for(int x = 9; x > -1; x--){
 cout << setw(2) << array2[x];
}
} 

将此更改为:

void reverseList(int array1[], int array2[]){
for(int i = 0; i < 10; i++){
  array2[9-i] = array1[i];
}
}

我认为,如果您将我的所有答案放在一起,您应该或多或少会有一些有用的东西。不过我自己还没有测试过。

关于c++ - 程序异常输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16079212/

相关文章:

c++ - 移动构造函数会自动初始化未列出的成员吗?

c++ - 如何在 C 中反转以下算法

c++ - 用C++编写正则表达式的正确方法是什么?

c++ - Project3.exe : 0xC0000005: Access violation reading location 0x00000003 中 0x00C61540 处的未处理异常

android - 生成跨平台应用

c++ - 在初始化之前使用任何自动变量

c++ - 如何从 libcurl 获取 URL 的片段部分?

c++ - 使用头文件中定义的全局变量

C++ 警告 : division of double by zero

c++ - 使用 boost::asio(visual studio12, x64) Unresolved external 问题