开发者

taking input from a file_2

开发者 https://www.devze.com 2023-04-12 08:47 出处:网络
i am taking input from a file row-wise...each row contains three or less columns... everything is fine if the line in the file is like

i am taking input from a file row-wise...each row contains three or less columns... everything is fine if the line in the file is like

     lda #5           

or

label +lda #5

but if a line starts with '+' like

+lda #5

that line is not being input....why is this so?

the input taking code is

ifstream in(asmfile,ios::in);
char c;
string str[3];
string subset;
long locctr=0;
int i=0;


while((c=in.get())!=EOF)
{
    in.putback(c);
    str[0]="";
    str[1]="";
    str[2]="";
    i=0;

    while((c=in.get())!='\n' && c!=EOF)
    {

        in.putback(c);
        in>>str[i++];

开发者_JAVA百科    }
}


I'm not sure where you were trying to go with your code, but it seems very poorly constructed to me, and you tagged the question as C++, so I would recommend you use the standard C++ idiom to read a file line by line:

#include <string>
#include <fstream>

std::ifstream infile(asmfile);
std::string line;

while (std::getline(infile, line))
{
  // process "line"
  // e.g. "lines.push_back(line);" , with "std::vector<std::string> lines;"
}


As written, I believe the posted code will read the lines shown as examples. In fact, I just now ran it, and it also read the line that you indicated would not work (and it reads just two "words" since the >> operator in that case will use white space as a delimiter for the string.

A possible reason for the failure is if the line preceding the +lda #5 line has more than three words (delimited by spaces). That would result in undefined behavior (quite possibly an access violation) since the str array has only three elements, and there is no check for the case where more than three words are on the line.

0

精彩评论

暂无评论...
验证码 换一张
取 消