我在排序char数组时遇到问题。有一个数组2 * 5 3 4应该从文件中排序,但我可以在代码中找到错误。编译器只是读取数组。任何建议,评论
#include <iostream> // cin cout endl
#include <fstream> // ifstream
#include <sstream> // stringstream
#include <stdlib.h> //exit
#include <vector>
#include "insertionSort.h";
using std::cerr;
using std::cout;
using std::endl;
using std::ifstream;
using std::vector;
using namespace std;
const int MAX_CHARS = 200; // max length of each line to read from the input file
template<class T>
void readSortOutput( char* typeName, vector<T> v, ifstream &inStream );
int main( )
{
int array_size= 1024;
char *array = new char[array_size];
int possition;
ifstream inStream("/home/xx/Downloads/input.txt");
cout << "Insertion sort algorithm driver program" << endl;
if( inStream.fail( ) )
{
cerr << "Input file opening failed.\n";
exit(1);
}
while (!inStream.eof()&&possition<array_size)
{
inStream.get(array[possition]);
possition++;
}
array[possition-1] = '\0';
cout <<"Display the array" <<endl <<endl;
for (int i=0;array[i] !='\0';i++)
{
cout <<array[i];
}
vector<int> intVector;
readSortOutput( (char*)"int", intVector, inStream );
vector<double> dblVector;
readSortOutput( (char*)"double", dblVector, inStream );
vector<char> chrVector;
readSortOutput( (char*)"char", chrVector, inStream );
inStream.close( );
return 0;
}
template<class T>
void readSortOutput( char* typeName, vector<T> v, ifstream &inStream )
{
// read a line from the input stream into a stringstream
char fileLine[MAX_CHARS];
std::stringstream ss;
inStream.getline(fileLine, MAX_CHARS);
ss << fileLine;
// extract elements of the specified type from the stringstream
T elem;
while (ss >> elem) {
v.push_back( elem );
}
cout << endl << typeName << " vector before insertion sort: " << endl;
for (int i = 0; i < v.size( ); i++)
cout << v[i] << " ";
cout << endl;
insertionSort( v ); // the sort itself
cout << typeName << " vector after insertion sort: " << endl;
for (int i = 0; i < v.size( ); i++)
cout << v[i] << " ";
cout << endl;
return;
} // readSortOutput
insertionSort.h
#ifndef INSERTIONSORT_H
#define INSERTIONSORT_H
#include <vector> // vector
#include <iostream> // cin cout endl
#include <fstream> // ifstream
#include <sstream> // stringstream
#include <stdlib.h> //exit
using std::vector;
/*template<class T>
void insertionSort(vector<T>& data); // function replaces the given argument
*/
template<class T>
void insertionSort(vector<T>& data)
{
for (size_t i = 0; i < data.size( ); i++)
for (size_t j = i; j < data.size( ); j++)
if (data[ j ] < data[ i ])
{ // swap values
T temp = data[ j ];
data[ j ] = data[ i ];
data[ i ] = temp;
}
return;
}
#endif // INSERTIONSORT_H
答案 0 :(得分:1)
while (!inStream.eof()&&possition<array_size)
{
inStream.get(array[possition]);
possition++;
}
当您浏览上面的循环时,您正在消耗所有输入。因此,当您致电readSortOutput
时,无需阅读任何内容。在尝试再次读取数组之前,您应该使用inStream.seekg(0);
重置文件中的位置。