string

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
closed account (3qX21hU5)
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
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?
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?
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!
is there any problem in my algorithm for reading from file and putting in string?!
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
Topic archived. No new replies allowed.