我有一个程序应该打印出 2 个列表,如下所示,基本上是相同的列表,但倒退了,但是它第一次工作但随后它打印了一些奇怪的输出,我也会在下面显示。
0123456789
9876543210
但是我从程序中得到的实际输出是这样的:
谁能告诉我我的代码有什么问题,我不确定为什么会得到这个输出。
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/