-4

Can someone please show me how to create an array function that reads from file txt string data type for example:

Read in the following files inside of a function:

colleges.txt

states.txt

Add the colleges/universities to a vector of strings.

Add the states to parallel arrays of strings.

Call the read function from your main function.

Thank you very much :D

Ike
  • 21
  • 1
  • 2
    You ask people to do your homework. There are plenty of topics about reading from files [for example this one](http://stackoverflow.com/questions/7868936/read-file-line-by-line) – ppsz Mar 05 '16 at 05:58

2 Answers2

-1

Try the following code:

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

void func()
{
    std::ifstream fin;
    fin.open("colleges.txt", std::ifstream::in);
    std::vector<std::string> vec;
    std::string line;
    while(getline(fin, line))
    {
        vec.push_back(line);
    }
    fin.close();

    int len = vec.size();
    std::string *arr = new std::string[len];
    int index = 0;
    fin.open("states.txt", std::ifstream::in);
    while(getline(fin, line))
    {
        arr[index++] = line;
    }
    fin.close();

    for(auto e:vec) std::cout<<e<<" ";
    std::cout<<"\n";

    for(int i = 0; i < len; ++i)
        std::cout<<arr[i]<<" ";
    std::cout<<"\n";

    delete [] arr;
}

int main()
{
    func();
    return 0;
}
YtRen
  • 13
  • 3
-1

use vectors, Carl!

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

using namespace std;

struct TwoVectors {
    vector<string> first ;
    vector<string> second;
};

TwoVectors getSomeData() {
    TwoVectors ret;

    auto collegesReader = ifstream("colleges.txt");
    auto statesReader = ifstream("states.txt");
    string temp;

    while (getline(collegesReader, temp))
        ret.first.push_back(temp);
    while (getline(statesReader, temp))
        ret.second.push_back(temp);
    collegesReader.close();
    statesReader.close();
    return ret;
}



int main() {
    auto someData = getSomeData();
    for (auto something : someData.first)
        cout << something << endl;
    for (auto something : someData.second)
        cout << something << endl;

    return 0;
}