Cannot get "goto" to work.

May 24, 2010 at 8:54pm
The code is 99% working, but I am now getting a compiler error. I am able to bubble sort and output all the names that start with the letter "A". However, when I try to output all my names that begins with "B", the go to "Next" statement gives a compiler error during compilation of the code. The error is "error C2362: initialization of 'i' is skipped by 'goto Next'".

#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
string fileName,line;
ifstream infile;
cout<<"Enter the file name and complete path: ";
cin>>fileName;
int Aa=0,Bb=0,count=0;
std::vector<string> A;
std::vector<string> B;
infile.open(fileName.c_str());
while(!infile.eof())
{
getline(infile,line);
if(line[count]=='A'||line[count]=='a')
{
A.push_back(line);
A[Aa]=line;
Aa++;
const size_t size = A.size();
for(size_t i=0; i<size; ++i)
{
for (size_t j=0; j<size-i-1;j++)
{
if (A[j+1].length() < A[j].length())// ascending order simply changes to <
{
A[j].swap(A[j+1]);
}
}
}
if(infile.eof())
{
cout <<endl<< "Sort result:" << endl;//show sort result
for (size_t y=0; y<size; ++y)
cout<<A[y]<<endl;
goto Next;
}
}
if(line[count]=='B'||line[count]=='b')
{
B.push_back(line);
B[Bb]=line;
Bb++;
const size_t size = B.size();
for(size_t i=0; i<size; ++i)
{
for (size_t j=0; j<size-i-1;j++)
{
if (B[j+1].length() < B[j].length())// ascending order simply changes to <
{
B[j].swap(B[j+1]);
}
}
}
Next: if(infile.eof())
{
cout <<endl<< "Sort result:" << endl;//show sort result
for (size_t y=0; y<size; ++y)
cout<<B[y]<<endl;
}
}
}
return 0;
}
May 24, 2010 at 8:59pm
Goto is considered bad style around here. Is there any way you can cut it out?

-Albatross
May 24, 2010 at 9:13pm
I only want to output the data after loop as ended, otherwise, I keep getting repetition of the output. I set up an if(eof) so that the output would not be repeating. At the end of the while loop, the if(eof) instructions does execute, but then it stops and does not go the next eof statement below. My reason for using goto was to tell the program exactly where to go after the first eof statement, but the goto is generating an error.
May 24, 2010 at 10:15pm
May 24, 2010 at 10:28pm
Good uses for goto are not easily come by.

I recommend you find a way not to use it in your example. The way you jump into the middle of an if construct is truly frightening.

I suggest not outputting the data until after the loop has ended and both As and Bs are ready.
Last edited on May 24, 2010 at 10:28pm
May 24, 2010 at 10:31pm
You don't need to put those "if (infile.eof())" constructs in the middle of the while loop because the loop will not continue if that condition is met anyway.

So its just to put the contents of your "if (infile.eof())" constructs after the loop, one after the other rather than inside.
Topic archived. No new replies allowed.