-1
所以我想創建此程序來檢查單詞列表的排序,以查看它們是升序還是降序。我將文件中的單詞複製到一個字符串數組中。我被告知常規比較運算符的功能與字符串的功能相同。但是,當我運行該程序時,它始終輸出該列表無序(即使是這樣)。我將不勝感激任何可以爲我提供的幫助。謝謝!檢查字符串數組排序:輸出不符合預期
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int checkArraySort(int array_max, string arr[]);
int main(void)
{
const int array_max = 20;
string arr[array_max];
int d;
ifstream myfile_in;
myfile_in.open ("words_in.txt");
string line;
for(int i = 0; i < array_max; i++)
{
getline(myfile_in, line);
}
d = checkArraySort(array_max, arr);
if(d == -1)
{
cout << "The array is sorted in descending order!" << endl;
}
if(d == 0)
{
cout << "The array is not sorted!" << endl;
}
if(d == 1)
{
cout << "The array is sorted in ascending order!" << endl;
}
myfile_in.close();
return 0;
}
int checkArraySort(int array_max, string arr[])
{
bool y = false;
int j = 0;
for(int i = 0; i < array_max; i++)
{
if(arr[i] < arr[i-1])
{
j++;
}
if(j == (array_max))
{
y = true;
return -1;
}
}
j = 0;
for(int i = 0; i < array_max; i++)
{
if(arr[i] > arr[i-1])
{
j++;
}
if(j == (array_max))
{
y = true;
return 1;
}
}
if(y = false)
{
return 0;
}
}
修改y = FALSE爲y = =假,順便說一句該條件總是爲true,根據您的代碼 – vishal
'y'是不必要的,因爲你之前只設置你'返回',所以沒有任何代碼可以看到變化。 – TartanLlama
而你的'getline'循環每次只覆蓋'line'。 – TartanLlama