Question

So I have this file titled "test.txt" the contents of this file is as follows:

once

twice

What I am trying to do is read this file, take it's contents line by line and append it into an array called "myarray" as seen below. Currently I am able to read the file, get a count of how many lines are in the file, but cannon figure out how to append each line into it's own index in my array.

Here's the code so far:

String filename = "C:\test.txt"    
Stream input = read filename
string str
int Number
int star = 0
while (true)
{
int NUMBER
input >> str
     if (end of input) break
     star++
}
NUMBER = star
string myarray[NUMBER] = {str}
print myarray[]`

In theory, i would like myarray[NUMBER] = {"once","twice"}

Any advice is much appreciated. Thanks!

Was it helpful?

Solution

There are two ways you can do this:

First method would be to loop through the file twice. The first time just to get a count of how many lines there are, then create your array with that many lines. Then you would loop through again to actually add each line to one of the array slots.

Example:

String filename = "C:\test.txt"    
Stream input = read filename
string str
int star = 0

while (true)
{
    input >> str
    if(end of input) break
    star++
}

string strArray[star]
input = read filename    
star = 0

while (true)
{
    input >> str
    if(end of input) break
    strArray[star] = str
    star++
}

// Do your code with the array here

The second method, and the easier way to do it, is to use a skip list instead of an array.

Example:

String filename = "C:\test.txt"    
Stream input = read filename
string str
int star = 0
Skip fileLines = create

while (true)
{
    input >> str
    if(end of input) break
    put(fileLines, star, str)
    star++
}

for str in fileLines do
{
    print str "\n"
}
delete fileLines

Don't forget the last line in there which is to delete the Skip list and release the resources.

OTHER TIPS

Elaborating on Steves answer and your request for something using arrays, the following is also possible:

string filename = "C:\\test.txt"    
Stream input = read filename
string str
int star = 0
Array fileLines = create(1,1)

while (true)
{
    input >> str
    if(end of input) break
    star++
    put(fileLines, str, star, 0)
}
put(fileLines, star, 0, 0)

int index, count = get(fileLines, 0, 0) // get the number of lines
for (index=1; index<=count; index++) 
{
    print (string get(fileLines, index, 0)) "\n"
}
delete fileLines

This uses an Array object, with the number of lines store in the first location. The other 'dimension' of the Array can be used to store information per line (e.g. count th enumber of words, etc).

Again, don't forget to delete Array object once you're done.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top