Need some help

Hello everyone i need some help figuring this out.

My question is asking me Write a program that creates an array of 100 string objects. Fill the array by having your program open a (text) file and read one line of the file into each string until you have filled the array. Display the array using the format “line #: <string>,” where # is the actual line number (you can use the array counter for this value) and <string> is the stored string.

Now when i compile this my line count starts at 0 and instead of 1 is this technically right what i have or is there another way of going about it?


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

using namespace std;

int main()
{

int i;
ifstream filename("input.txt");
string filesave[100];

for(i = 0; getline(filename, filesave[i])&&i<100; i++)
{
}
for(int x = 0; x<i; x++)
{
cout <<"line " << x << ": "<< filesave[x] << endl;
}
cin.get();
}
closed account (Dy7SLyTq)
just do cout<<"line "<< x + 1
Thank you very much DTSCode! greatly appreciated :]
I would rewrite the for loop as a while loop. For example


const int N = 100;
string filesave[N];

int i = 0;

while ( i < N && getline(filename, filesave[i] ) ) i++;

Also it is important what is the order of the logical subexpressions. In your code this order

getline(filename, filesave[i])&&i<100

is incorrect because it allows to execute subexpression getline(filename, filesave[100]).
Last edited on
I see what your saying Vlad, ok ill make some changes to it and let you guys know what i come up with.
fix your for loop.
since you know that you want to fill an array of 100 it should be simple like this...
1
2
3
4
5
for(int i=0; i<100; i++) {
string line;
getline(filename,line);
filesave[i] = line;
}


once you've filled the array, create a seperate loop to display it.
Last edited on
closed account (Dy7SLyTq)
that wont work manga because it will try to read after eof. he wants this
while((i < 100) && getline(filename, filesave[i]))
The file will stop reading once the array is full. Unless you mean the file is too short. If that is the case then he needs to chose a bigger file because he said he needs to fill an array of 100.
@Manga

The file will stop reading once the array is full. Unless you mean the file is too short. If that is the case then he needs to chose a bigger file because he said he needs to fill an array of 100.


There is a big difference between what you need and what you have.
Maybe if the file is too short he can start looping through the file again until the array is filled.
@Manga

Maybe if the file is too short he can start looping through the file again until the array is filled.



I think that the more correct approach is to read as many records as there are in a file but not greater than 100.
no. he clearly said fill the array until the array is filled.
Topic archived. No new replies allowed.