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

标签 c++ sorting c++11

我创建了一个程序来按字母顺序对文本文件中的所有内容进行排序。但是,如果同一行上的 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 将读取整行。

此外,using eof in a loop condition is BadTM .

关于c++ - 如何仅按行排序,而不是 C++ 中的行和/或空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35807680/

相关文章:

python - 组织两列数据

c++ - 通过引用修改单独函数中 Rcpp::List 的子部分

c++ - 标识符错误之前缺少 ';' - 无法运行 MPI 示例

java - Java 中 int[] 原始数组排序的优化且高效的方法

mysql - 如何在 mySQL 中自定义排序顺序并检查字符串的开头?

c++ - `sizeof` *真的*评估为 `std::size_t` 吗?它可以?

C++:语句 'TYPE& name(&TYPE);' 是什么意思?

javascript - 如何在 cef 框架中支持 window.external.xxx

c++ - 在 Visual Studio 2013 中链接 NuGet 库

c++ - include 如何使用软链接(soft link)?