如何仅按行排序,而不是按行和/或C++中的空格排序
How to sort by line only, NOT by line and/or space in C++
我创建了一个程序,按字母顺序对文本文件中的所有内容进行排序。但是,如果同一行上的 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。
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- clang格式:禁用排序包含
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 试图在c++中对数字列表进行排序
- 如何在C++中对数组进行冒泡排序