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

时间:2012-05-02 11:54:51

标签: c++

我是一名物理博士生,有一些java编程经验,但我正在努力学习C ++。

我想解决的问题是从.txt文件中读取数据然后输出所有数字> 1000在一个文件中,所有那些< 1000在另一个文件中。

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

 #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();
}

但如果它更容易,我会再次开始整个事情,因为我不完全清楚所有复制的代码在做什么。总而言之,我需要的是 -

在控制台中询问文件路径 打开文件,并将每个数字(以空格分隔)存储为1D数组中的元素

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

非常感谢

4 个答案:

答案 0 :(得分:4)

使用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;
}

答案 1 :(得分:2)

只需将从new std:ifstream("path to file")创建的变量输入到你的headream的类型转换为int,c ++将为你完成工作

答案 2 :(得分:1)

#include <fstream> //input/output filestream
#include <iostream>//input/output (for console)

void LoadFile(const char* file)
{
    int less[100]; //stores integers less than 1000(max 100)
    int more[100]; //stores integers more than 1000(max 100)
    int numless = 0;//initialization not automatic in c++
    int nummore = 0; //these store number of more/less numbers
    std::ifstream File(file); //loads file
    while(!file.eof()) //while not reached end of file
    {
        int number;      //first we load the number
        File >> number;  //load the number
        if( number > 1000 )
        {
             more[nummore] = number;
             nummore++;//increase counter
        }
        else
        {
            less[numless] = number;
            numless++;//increase counter
        }
    }
    std::cout << "number of numbers less:" << numless << std::endl; //inform user about
    std::cout << "number of numbers more:" << nummore << std::endl; //how much found...
}

这应该可以让你知道它应该是什么样的(你很难使用静态大小的数组)如果你有任何probs,请回复

另外,请尝试制作好的可读代码,并使用制表符/ 4个空格。

答案 3 :(得分:0)

即使它是纯粹的C,这可能会给你一些提示。

#include <stdio.h>
#include <stdlib.h>
#include "string.h"

#define MAX_LINE_CHARS 1024

void read_numbers_from_file(const char* file_path)
{
    //holder for the characters in the line
    char contents[MAX_LINE_CHARS];
    int size_contents = 0;

    FILE *fp = fopen(file_path, "r");
    char c;
    //reads the file
    while(!feof(fp))
    {
        c = fgetc(fp);
        contents[size_contents] = c;
        size_contents++;
    }

    char *token;
    token = strtok(contents, " ");
    //cycles through every number
    while(token != NULL)
    {
        int number_to_add = atoi(token);
        //handle your number!
        printf("%d \n", number_to_add);
        token = strtok(NULL, " ");
    }

    fclose(fp);
}

int main()
{

    read_numbers_from_file("path_to_file");

    return 0;
}

读取一个用空格分隔的数字文件并打印出来。

希望它有所帮助。

干杯

相关问题