Help with ifstream

Good day, I just need some help on how to stop outputting data based on a user input.

The text file is as follows:
1
2
3
4
1. a
2. b
3. c


and the code I'm using is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main (){
string line;
int search;
cout << "Enter a number from 1-3" << endl;
cin >> search;
search++;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
  	
    while( !myfile.eof() && line != search)
    {
    	getline (myfile,line);
      cout << line << endl;

    }
    myfile.close();
  }

else cout << "Unable to open file"; 

return 0;
}


What I want to do is to just output number 1 (the whole line) if the user enters
number 1. However, I get an error on the second condition w/c is the "&& line!= search"

Appreciate the help. Thanks mates.

Last edited on
closed account (o3hC5Di1)
Hi there,

Please wrap your code in [code][/code]-tags, I've added some comments:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main (){
string line;
int search; //You declare search as an int here
cout << "Enter a number from 1-3" << endl;
cin >> search;
search++;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
//here you ask the compiler to compare a string to an int, 
// that won't work without converting one to the other.
while( !myfile.eof() && line != search) 
{
getline (myfile,line);
cout << line << endl;

}
myfile.close();
}

else cout << "Unable to open file";

return 0;
}


You will need to convert the first character of the line string to a number in oder to compare it to search. String to number conversion functions are available in the std::string library: http://www.cplusplus.com/reference/string/

Hope that helps.

All the best,
NwN
Topic archived. No new replies allowed.