我正在编写一个程序,需要从.txt文件中对引号进行排序并输出到另一个文件。我试图放入一个数组进行排序的QUOTES.txt文件有这样的引号
如果你达到了标记,你必须瞄准它的上方;每一个箭头 苍蝇感受到地球的吸引力。 Henry Wadsworth Longfellow
永远,绝不,永不放弃!温斯顿丘吉尔
伟大的作品不是靠力量而是靠坚持不懈。 塞缪尔约翰逊
由于缺乏目标而缺乏人才,更多的人失败了。比利星期天
孩子们从未擅长倾听长辈,但他们 从来没有模仿过他们。詹姆斯鲍德温
无需更改模板,有没有办法对完整的句子进行排序?现在它正在单独输入单词并对单词进行排序,但我希望句子保持不变,只能按句子的第一个字母排序。这是我写的代码:
#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);
}
---------- EDIT ---------------
我将inWords
的输入从inWords >> data3[i];
更改为getline(inWords, data3[i];
,所以现在它一次扫描一行。现在我只需要找出如何对这个新数组进行排序并保持引号不变。
答案 0 :(得分:1)
很抱歉,我并没有将解决方案纳入您现有的代码,但这绝对有效:
#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;
}