print array in own line

closed account (G60iz8AR)
How do you print an array in its own line ?

// Filter: print every word from the array on its own line.
// Before each word print line # and a TAB

#include <string> // string class
#include <iostream> // cin, cout: console I/O
#include <fstream> // ifstream, ofstream: file
#include <stdlib.h>
using namespace std;

const int CAP = 500;

int main()
{
ifstream infile;
string arr[ CAP ]; // CAPACITY is 500
int count=0; // how many strings stored in array so far

// TRY TO OPEN THE INPUT FILE "words.txt"
infile.open("words.txt", ios::in);
if ( infile.fail() )
{
cout << "Can't find words.txt. Are you sure it's in this directory? (do a dir command).\nDoes it accidentally have a .txt.txt extension?\n";
exit(0);
}

while( count < CAP && infile >> arr[count] )
count++;
infile.close();

cout << count << " words stored into array from words.txt\n" ;
cout << "Now printing each word on its own line with line numbers:\n";

// Y O U C H A N G E T H E C O D E I N T H E L O O P B O D Y S O T H A T
// E A C H W O R D I S P R I N T E D O N I T S O W N L I N E
// W I T H L I N E N U M B E R S


for ( int i=0 ; i< count ; i++ )
{
// YOUR CODE HERE do not change anyting else in this starter file
}

return 0;
}
this is how i will read a file word by word:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main ()
{
    ifstream var( "var.txt" );
    
    if ( var.fail() ) return 0;
    else {
        string line;
        int count = 1;
        
        while ( var >> line ) {
            cout << "Line " << count << ": " << line << endl;
            count++;
        }
    }
    return 0;
}


EDIT: Ohh, i didn't see, that your source is an array:
Last edited on
1
2
3
4
5
for ( int i=0 ; i< count ; i++ )
{
    // YOUR CODE HERE do not change anyting else in this starter file
    cout << i + 1 << "\t" << arr[i] << endl;
}
Topic archived. No new replies allowed.