string
Mar 26, 2013 at 6:55pm UTC
why it gives string subscript out of range error?!
1 2 3 4 5 6 7 8 9 10 11 12 13
void main(vector<and> ands,vector<or> ors,vector<xor> xors,vector<nand>nands)
/////////////////////////reading file
{vector<string>help;
help.clear();
ifstream input;
input.open("test.txt" );
string line;
while (!input.eof()){
getline(input,line);
help.push_back(line);
line.clear();
}
input.close();
Last edited on Mar 26, 2013 at 7:53pm UTC
Mar 26, 2013 at 7:39pm UTC
Well first off why are you declaring
void main(vector<and> ands,vector<or> ors,vector<xor> xors,vector<nand>nands)
There can only be one main and that is not one of the ways to declare it. The simplest is this
1 2 3 4
int main()
{
return 0;
}
That is all I wanted to comment on also please use codetags when posting code to the forums (Hint: Highlight code then press <> button)
Last edited on Mar 26, 2013 at 7:40pm UTC
Mar 26, 2013 at 7:58pm UTC
I have classes named and,or...and in main I need their members so I declared main as those classes friend,do you mean that kind of declaring main is wrong?
Mar 26, 2013 at 9:36pm UTC
If you need to use the classes, just declare within the main block.
1 2 3 4 5 6 7 8
int main(){
//And the alternative vector <foo> bar; for your containers too.
and ands;
or ors;
xor xors;
nand nands;
//...Whatever code
}
Also, did you just forget to include the closing bracket to your main when copy/pasting?
Mar 26, 2013 at 9:55pm UTC
yes,I just forgot that bracket in copy pasting.
I changed the way of declaring main function as you said.but my code still have that previous error!
Mar 26, 2013 at 9:58pm UTC
is there any problem in my algorithm for reading from file and putting in string?!
Mar 26, 2013 at 10:17pm UTC
This loop is flawed:
1 2 3 4 5 6
while (!input.eof())
{
getline(input,line);
help.push_back(line);
line.clear();
}
at line 3 (above), the getline is performed. But regardless of whether or not it was successful, the next two lines are executed - in particular the push_back() which may add an empty line to the vector.
A recommended way is to not use eof() at all.
1 2 3 4
while (getline(input,line))
{
help.push_back(line);
}
Last edited on Mar 26, 2013 at 10:18pm UTC
Topic archived. No new replies allowed.