Arrarys
2 ビュー (過去 30 日間)
古いコメントを表示
I am reading in two text files, and placing the contents into an array element. In my code I am prompting the user for the number of students and questions. I am then to randomly select a student and question and output to the screen. Continue this until a 0 or -1 is entered.
I have written code but I am not sure if it is correct. Can someone please take a look and tell me how far off I am and what corrections need to be made. Thanks.
inFile=fopen('student.txt','r');
inFile2=fopen('testQuestion.txt','r');
flag=-1;
index=0;
student=[];
testQuestion=[];
while~feof(inFile)
index=index+1;
line=fgetl(inFile);
end
while~feof(inFile2)
index=index+1;
line=fgetl(inFile2);
end
while student~=-1
student=rand(1,5);
end
while testQuestion~=-1
testQuestion=rand(1,5);
end
fprintf('%s',student)
fprintf('%s',testQuestion)
0 件のコメント
回答 (1 件)
Walter Roberson
2011 年 11 月 14 日
while~feof(inFile)
should not be relied upon to be accepted in future versions. You should use a space between the while and the condition.
You are using feof() as if it predicts end-of-file, as if after after the last item in the file is read, the I/O routines would look ahead and see that nothing is left and would set the feof flag. Anything based upon the C or C++ I/O libraries or upon the OpenGroup Unix Standards or upon the POSIX standards (and MS Windows claims POSIX conformance in this regard) never does that kind of "look-ahead". Instead, feof is not set until an I/O operation attempts to read data and there is absolutely no data available. Therefore, each time you fgetl() you need to test whether that was the I/O that found end-of-file. And it turns out that the easiest way to do that does not need feof at all:
while true
line = fgetl(inFile);
if ~ischar(line) %at EOF, non-char is returned
break;
end
index = index + 1;
end
I admit to being puzzled as to why you are not storing the content of the lines you read...
You initialize
student=[];
testQuestion=[];
If you do some testing, you will find that
if [] == -1
and
if [] ~= -1
are both false. Perhaps you meant to set student and testQuestion to something along the way, but we cannot tell what.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Get Started with MATLAB についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!