如何仅按行排序,而不是按行和/或C++中的空格排序

How to sort by line only, NOT by line and/or space in C++

本文关键字:排序 C++ 空格 何仅按      更新时间:2023-10-16

我创建了一个程序,按字母顺序对文本文件中的所有内容进行排序。但是,如果同一行上的 2 个或多个单词之间有空格,它将识别它们是分开的。我想防止这种情况。

我试图让它只排序行。所以例如:

橙子苏打水

百事可乐

可口可乐

成为...

可口可乐

橙子苏打水

百事可乐

不。。。。。。

古柯

可乐

百事可乐

苏打

#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将读取整行。

此外,在循环条件下使用 eof 是错误的TM。