我似乎无法弄清楚我在做什么错。我今天在类里面记笔记,但是很不幸,我的OneNote崩溃了,并删除了今天的所有笔记。我知道我缺少一些东西,但是我无法弄清楚。我一直在搜索我的课本,甚至在网上看了一个多小时。我似乎找不到任何有效的方法。
我知道我的错误可能是我在if或set变量语句中使用charPtr ++的事实,但是我不记得该怎么做。如何检查一个元素是否少于另一个?
我们应该使用指针算术来编写10个元素的降序冒泡排序。有人可以解释我做错了什么,为什么我的程序除了原始数组外不输出任何东西?谢谢!
我们也不能使用括号或偏移量表示法。
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// DRIVER PROGRAM
char *characters, *charPtr = nullptr; // Array or undefined size.
fstream fs; // file stream for file arithmetic
fs.open("array.txt", ios::in); // Open the file
char currentChar; // Used to check if the file can still be read.
int counter = 0; // Counter to check how many elements are in the array.
while (fs >> currentChar) { // While data can be put into counter, continue...
counter++; // Add one to counter
}
characters = new char[counter]; // Sets size of array.
charPtr = characters;
fs.clear(); // Clears eof flag.
fs.seekg(0, ios::beg); // Sets pointer back to the beginning. CHECK IF YOU CAN REMOVE THIS LINE AND THE ONE ABOVE.
for (int i = 0; i < counter; i++) { // While less than the size of array.
fs >> charPtr; // Write to charPtr
cout << *charPtr << " "; // Output array.
charPtr++; // Move to next element
}
fs.close(); // Close file
putchar('\n'); // Output newline efficiently.
charPtr = characters;
// BUBBLE SORT
bool swapChar;
char temp;
do {
swapChar = false;
for(int count = 0; count < (counter - 1); count++) {
if (*(charPtr) < *(charPtr++)) { // If character at 0 is less than the character at 1
temp = *(charPtr); // Set temp to character at 0
*(charPtr) = *(charPtr++); // set character at 0 to character at 1
*(charPtr++) = temp; // set character at 1 to temp
swapChar = true; // set swap to true
cout << *charPtr << " "; // output current swap
charPtr++; // add 1 to charPtr
}
}
} while (swapChar == true);
}
最佳答案
请记住,charPtr++
会自己增加。在下面的代码块中,您执行了4个增量,并且您只希望执行一次。您应该改为用*(charPtr+1)
代替。
if (*(charPtr) < *(charPtr++)) { // If character at 0 is less than the character at 1
temp = *(charPtr); // Set temp to character at 0
*(charPtr) = *(charPtr++); // set character at 0 to character at 1
*(charPtr++) = temp; // set character at 1 to temp
swapChar = true; // set swap to true
cout << *charPtr << " "; // output current swap
charPtr++; // add 1 to charPtr
}