我创建了一个程序来按字母顺序对文本文件中的所有内容进行排序。但是,如果同一行上的 2 个或更多单词之间有空格,它会将它们识别为分开的。我想阻止这种情况。
我试图让它只对行进行排序。例如:
Orange Soda
Pepsi
Coca Cola
成为……
Coca Cola
Orange Soda
Pepsi
不......
Coca
Cola
Orange
Pepsi
Soda
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ifstream sortFile("list.txt");
string theArray[9999], temp;
int count=0, x, y;
if(!sortFile.is_open()){
cout << "Cannot find \"list.txt\" in the current directory." << endl;
}
// determine how many separate list items
while(!sortFile.eof()){
sortFile >> theArray[count];
count++;
}// while
// arrange array in alphabetical order
for(x=0;x<count;x++){
for(y=0;y<count;y++){
if(theArray[x]<theArray[y]){
temp = theArray[x];
theArray[x] = theArray[y];
theArray[y] = temp;
}// if
}// for y
}// for x
// save to file
ofstream saveFile("fixed.txt");
for(x=0;x<count;x++){
if(theArray[x]!=theArray[x+1]){
if(count-1==x){
saveFile << theArray[x];
}else{
saveFile << theArray[x] << endl;
}// if else
}else{
saveFile << theArray[x] << " ";
}// if else
}// for
saveFile.close();
cout << "Completed Sucessfully! Look for a file named \"fixed.txt\"";
cin.get();
}
提前致谢!
最佳答案
将您的 while
循环替换为:
while(std::getline(sortFile, theArray[count++]));
流的 >>>
运算符以空格分隔,但 getline
将读取整行。
关于c++ - 如何仅按行排序,而不是 C++ 中的行和/或空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35807680/