gpt4 book ai didi

C++程序读取txt文件并对数据进行排序

转载 作者:行者123 更新时间:2023-11-30 00:38:33 25 4
gpt4 key购买 nike

我是一名物理博士生,具有一些 Java 编码经验,但我正在尝试学习 C++。

我要解决的问题是从 .txt 文件中读取数据,然后在一个文件中输出所有大于 1000 的数字,在另一个文件中输出所有小于 1000 的数字。

我需要帮助的是编写实际读取数据并将其保存到数组的代码部分。数据本身只用一个空格分隔,而不是全部换行,这让我有点困惑,因为我不知道如何让 c++ 将每个新单词识别为 int。我已经对从各种在线来源获得的一些代码进行了 canabalised-

 #include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include<cmath>

using namespace std;

int hmlines(ifstream &a) {
int i=0;
string line;
while (getline(a,line)) {
cout << line << endl;
i++;
}
return i;
}

int hmwords(ifstream &a) {
int i=0;
char c;
a >> noskipws >> c;
while ((c=a.get()) && (c!=EOF)){
if (c==' ') {
i++;
}
}
return i;
}

int main()
{
int l=0;
int w=0;
string filename;
ifstream matos;
start:
cout << "Input filename- ";
cin >> filename;
matos.open(filename.c_str());
if (matos.fail()) {
goto start;
}
matos.seekg(0, ios::beg);
w = hmwords(matos);
cout << w;
/*c = hmchars(matos);*/

int RawData[w];
int n;

// Loop through the input file
while ( !matos.eof() )
{
matos>> n;
for(int i = 0; i <= w; i++)
{
RawData[n];
cout<< RawData[n];
}
}

//2nd Copied code ends here
int On = 0;

for(int j =0; j< w; j++) {
if(RawData[j] > 1000) {
On = On +1;
}
}

int OnArray [On];
int OffArray [w-On];

for(int j =0; j< w; j++) {
if(RawData[j]> 1000) {
OnArray[j] = RawData[j];
}
else {
OffArray[j] = RawData[j];
}
}

cout << "The # of lines are :" << l
<< ". The # of words are : " << w
<< "Number of T on elements is" << On;

matos.close();
}

但如果它会更容易,我愿意重新开始整个事情,因为我不明白所有复制的代码到底在做什么。所以总而言之,我需要的是——

在控制台中请求一个文件路径打开文件,并将每个数字(以空格分隔)作为一个元素存储在一维数组中

如果我能让它按照我需要的方式读取文件,我认为我可以自己管理实际操作。

非常感谢

最佳答案

使用 C++11 和标准库可以让您的任务变得相当简单。这使用标准库容器、算法和一个简单的 lambda 函数。

#include <algorithm>
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <vector>

int main()
{
std::string filename;
std::cout << "Input filename- ";
std::cin >> filename;

std::ifstream infile(filename);
if (!infile)
{
std::cerr << "can't open " << filename << '\n';
return 1;
}
std::istream_iterator<int> input(infile), eof; // stream iterators

std::vector<int> onvec, offvec; // standard containers

std::partition_copy(
input, eof, // source (begin, end]
back_inserter(onvec), // first destination
back_inserter(offvec), // second destination
[](int n){ return n > 1000; } // true == dest1, false == dest2
);

// the data is now in the two containers

return 0;
}

关于C++程序读取txt文件并对数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10413217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com