Reading text file into an array
Can someone tell me how to create a function to read a text file into an array? The function main must contain function calls.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
std::vector<std::string> readLinesFromFile(const std::string& fileName)
{
std::vector<std::string> linesInFile;
std::ifstream inputFile(fileName);
if (inputFile)
{
std::string tempLine;
while (inputFile >> tempLine)
{
std::getline(inputFile, tempLine);
linesInFile.push_back(tempLine);
}
}
else
{
std::cout << "File \"" << fileName << "\" could not be opened.\n";
}
return linesInFile;
}
int main()
{
const std::string nameOfFile = "input.txt";
std::vector<std::string> lines = readLinesFromFile(nameOfFile);
std::cout << lines.size() << " line(s) were read from the file.\n";
}
|
Something like this if the text file has numbers
1 2 3
|
infile >> array[0];
for(size_t i = 1; infile; i++)
infile >> array[i];
|
Or like this if it has strings
1 2 3
|
getline(infile, array[0]);
for(size_t i = 1; infile; i++)
getline(infile, array[i]);
|
Topic archived. No new replies allowed.