因此,我有一个名为"test.txt“的文件,该文件的内容如下:
一次
两次
我要做的是读取这个文件,逐行获取它的内容,并将其附加到一个名为"myarray“的数组中,如下所示。目前,我能够读取文件,得到文件中有多少行,但是cannon想出了如何将每一行附加到数组中它自己的索引中。
以下是目前为止的代码:
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[]`理论上,我希望myarrayNUMBER ={“一次”,“两次”}
任何建议都是非常感谢的。谢谢!
发布于 2013-08-14 15:53:44
有两种方法可以做到这一点:
第一种方法是循环遍历文件两次。第一次仅仅是为了计算出有多少行,然后用这么多行创建数组。然后再循环一次,将每一行实际添加到一个数组插槽中。
示例:
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第二种方法,也是更简单的方法,是使用跳过列表而不是数组。
示例:
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不要忘记其中的最后一行,即删除Skip列表并释放资源。
发布于 2013-09-02 13:58:23
在阐述Steves的回答和您对使用数组的请求时,还可以使用以下内容:
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这使用了Array对象,其中存储在第一个位置的行数。数组的另一个“维”可以用来存储每一行的信息(例如,单词的计数,等等)。
同样,一旦完成,不要忘记删除Array对象。
https://stackoverflow.com/questions/18234705
复制相似问题