我正在编写一个程序,需要对.txt文件中的引号进行排序,并将其输出到另一个文件。我试图放入数组中进行排序的QUOTES.txt文件有如下引号
如果你想击中目标,你必须瞄准它上面一点,每一支飞起来的箭都能感受到地球的吸引力。亨利·沃兹沃斯·朗费罗 永远,永远,永不放弃!温斯顿·丘吉尔 没有恒心只有力量是完不成伟业。塞缪尔·约翰逊 由于缺乏目标而失败的人比缺乏才能的人多。比利·桑迪 孩子们从来不善于听长辈的话,但他们从来没有不模仿他们。鲍德温
不需要改变我的模板,有没有办法对整句话进行排序?现在,它是逐个输入单词,并对单词进行排序,但我希望这些句子保持原样,并且只按句子的第一个字母排序。下面是我编写的代码:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
template < typename T >
T sorting(T rays [], int size)
{
int minIndx, i;
T temp;
for (int passCount = 0; passCount < size - 1; passCount++)
{
minIndx = passCount;
for (int searchIndx = passCount + 1; searchIndx < size; searchIndx++)
if (rays[searchIndx] < rays[minIndx])
minIndx = searchIndx;
temp = rays[minIndx];
rays[minIndx] = rays[passCount];
rays[passCount] = temp;
}
cout << endl << "Sorted:" << endl;
for (i = 0; i < size; ++i)
cout << rays[i] << endl;
cout << endl;
return (0);
}
int main()
{
ifstream inNumbers("IntFile.txt");
ifstream inFloaters("FloatFile.txt");
ifstream inWords("QUOTES.txt");
ofstream outNumbers("SortedInt.txt");
ofstream outFloaters("SortedFloat.txt");
ofstream outWords("SortedQuotes.txt");
int i, length = 0, lengt = 0, leng = 0;
int data[100];
double data2[100];
string data3[100];
if (!inNumbers)
{
cerr << "IntFile.txt file could not be opened" << endl;
exit(1);
}
if (!inFloaters)
{
cerr << "FloatFile.txt file could not be opened" << endl;
exit(1);
}
if (!inWords)
{
cerr << "QUOTES.txt file could not be opened" << endl;
exit(1);
}
for (i = 0; i < 100 && inNumbers; ++i)
{
inNumbers >> data[i];
if (inNumbers)
{
length += 1;
}
}
sorting(data, length);
for (i = 0; i < 100 && inFloaters; ++i)
{
inFloaters >> data2[i];
if (inFloaters)
{
lengt += 1;
}
}
sorting(data2, lengt);
for (i = 0; i < 100 && inWords; ++i)
{
inWords >> data3[i];
if (inWords)
{
leng += 1;
}
}
sorting(data3, leng);
}-编辑
我将inWords的输入从inWords >> data3[i];更改为getline(inWords, data3[i];,因此现在它一次扫描一行。现在,我只需要找出如何排序这个新的数组,但仍然保持引号不变。
发布于 2015-02-05 22:16:00
对不起,我并没有把解决方案合并到您现有的代码中,但这肯定有效:
#include <iostream>
#include <string>
#include <fstream>
#include <cassert>
#include <vector>
using namespace std;
int main() {
ifstream iFile("QUOTES.txt");
assert(iFile.is_open());
vector<string> quoteLines, quotes;
for (string s; getline(iFile, s);) quoteLines.push_back(s);
iFile.close();
/* deal with multi-line quotes by merging the stuff separated
by empty lines into single strings */
string tmpStr;
for (const auto& s : quoteLines) {
if (s == "") {
/* if we come across an empty line, put the stuff we had so far into the vector
and clear the temporary string */
quotes.push_back(tmpStr);
tmpStr.clear();
} else {
/* if there's already stuff in the temporary string, then append a space to it. */
/* then, append the current line */
tmpStr += ((tmpStr.size() == 0)?"":" ") + s;
}
}
/* sort the quotes */
sort(quotes.begin(), quotes.end());
for (const auto& s : quotes) cout << s << endl << endl;
return 0;
}https://stackoverflow.com/questions/28353961
复制相似问题