-1

Hey guys I stuck working on an assignment in which I asked to write a program that lists the contents of a file.

#include<iostream>
#include<fstream>
using namespace std;
int main() {

string array[5];

ifstream infile("file_names.txt");

int x=0;
while(infile>>array[x++]){

    for(int i=0;i<=x;i++){

    infile >> array[i];

    cout << array[i] << endl;}}

    }

basically I have a file named "file_names.txt" that contains three strings and I want my program to list them.

katze
  • 13
  • 1

3 Answers3

1

you don't need two loops.

int main() {
int array_size=5;
string array[array_size];

ifstream infile("file_names.txt");

int x=0;int i=0;
while(i<array_size && infile>>array[i]){ //order is important here
    cout << array[i] << endl;
    i++;
    }

}
GorvGoyl
  • 27,835
  • 20
  • 141
  • 143
  • `infile >> array[i]` should be the loop condition, otherwise this is almost as bad as [checking eof](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – M.M Mar 26 '15 at 23:34
  • @MattMcNabb thnks for the pro tip. – GorvGoyl Mar 26 '15 at 23:41
  • @JackArcher action speaks louder than words.mark the answer. – GorvGoyl Mar 27 '15 at 00:00
0

Your assignment was

an assignment in which I asked to write a program that lists the contents of a file.

One way of printing the contents of a file could be

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

using namespace std;

int main()
{
    ifstream fin("my_file.txt", ios::in); // open input stream

    if(!fin){ // check state, that file could be successfully opened
        printf("Error opening file.");
        return 1;
    }

    while(fin.peek() != EOF){
        cout << (char)fin.get();
    }

    fin.close(); // close input stream

    return 0;
}

This code demonstrates some basic C++ functionality like opening an input stream, checking the state of the input stream and reading the contents character by character. Try to understand each step.

jensa
  • 2,552
  • 1
  • 17
  • 31
0

I know I can get to the same result like this

string array[50];

ifstream infile("file_names.txt");

for(int i=0; **i<3**; i++){

    infile >> array[i];

    cout << array[i] <<endl;}

But the whole point is to use a while loop because there might be more or less than 3 items

katze
  • 13
  • 1