从文件中读取数据并进行操作

时间:2015-01-01 05:45:56

标签: c++

#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>

using namespace std;

int main(){

    //Declare file streams & open the file
    ifstream input;
    input.open("price.txt");

    if(input.fail())
    {
        cout << "price.txt could not be accessed!" << endl;
        exit(1);
    }

    string temp, test; //String data from file, to be converted to an double

    //Get data from file
    for(int i = 1; i <= 10; i++)
    {
        if(!input.eof()){
            getline(input,temp); //Get 1 line from the file and place into temp
            cout<< i << ". " << temp <<"\n";
            test[i] = atof(temp.c_str()); //set the test variable to the double data type of the line

        }
    }

    input.close();
    return 0;
}

问题是我如何使用从文件中获取的数据来分配给另一个变量,这样我就可以将变量用于整个c ++程序

我的txt文件看起来像

3.00
4.00
5.00
3.20
3.00
3.55
1.60
4.90
2.00
1.50

2 个答案:

答案 0 :(得分:0)

以下是必修课程:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

int main(){
    ifstream input; //Declare file streams & open the file
    input.open("C:\\price.txt");

    if (input.fail())
    {
        cout << "price.txt could not be accessed!" << endl;
        getchar();
        exit(1);
    }

    int k = 0;
    double price[200] = { 0.0 }; // allocate this array a size suitable to your application.
    for (int i = 1; i <= 10; i++)
    {
        if (!input.eof()){
            string temp;
            getline(input, temp); //Get 1 line from the file and place into temp
            cout << i << ". " << temp << "\n";

            string arr[20]; // allocate this array a size suitable to your application.
            int j = 0;
            stringstream ssin(temp);
            while (ssin.good() && j < 20){
                ssin >> arr[j];
                ++j;
            }
            for (int a = 0; a < j; a++){
                cout << arr[a] << endl;
                if (arr[a] != "" && arr[a] != " "){
                    price[k] = stod(arr[a]);
                    k++;
                }
            }
        }
    }
    cout << "prices are:" << endl;
    for (int b = 0; b < k; b++){
        cout << price[b] << endl;
    }

    input.close();
    getchar();
    return 0;
}

仅供参考:我使用过VS2013并将文件price.txt存储在c:\

希望这有帮助。

答案 1 :(得分:0)

如果您可以使用<vector&gt;,那么您的生活会更轻松。

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

using namespace std;

void getItems(vector<double>& v, string path)
{
    ifstream is(path.c_str());
    istream_iterator<double> start(is), end;
    vector<double> items(start, end);
    v = items;
}

int main()
{
    vector<double> v;
    getItems(v, <PATH_TO_YOUR_FILE>);

    vector<double>::iterator it;
    for(it = v.begin(); it != v.end(); it++)
        cout << *it << endl;

    return 0;
}