Hello Guys,

I've tried my best but it won't work.

I'm trying to read an integer from a txt file and return the whole line where this integer resides.

So, for example, in my txt file, if I have a line: aaa bbb ccc 100 bb 9
and I type in: 100

It'd return: bb 9

I want it to return the whole line.

Here's the compilable code:

#include <iostream>
#include <fstream>
using namespace std;

ifstream in;
ofstream out;
char a[255];
char b[255];

void search (char b[]) {
	while (!in.eof())
	{
		in >> a;
		if (strcmp(a,b)==0) {
			in.getline(a,255);
			cout << a <<endl;
		}
	}
}

int main() 
{
	in.open("test.txt");
	if(in.fail()) {
		cout << "Couldn't open!";
	}
	cin >> b;
	search(b);
	in.close();
	return 0;
}

test.txt:

aaa bbb ccc 100 ddd 0
bbb aaa ccc 200 ddd 1

Thanks for your help!

Comments
Used code tags correctly on first post!

It's not displaying the whole line because you are overwriting a in this function:

void search (char b[]) {
	while (!in.eof())
	{
		in >> a;
		if (strcmp(a,b)==0) {
			in.getline(a,255);
			cout << a <<endl;
		}
	}
}

You're using the >> operator. Take the line:

aaa bbb ccc 100 ddd 0

Let b = "100".

"aaa" is read into a. "aaa" is compared to "100". It doesn't match, so read the next string into a.

"bbb" now is stored in a. "aaa" is now stored nowhere, so you already have a problem. You need to read in a line at a time. Don't use the >> operator. Read the whole line:

aaa bbb ccc 100 ddd 0

into a at once using getline. Check whether b ("100") is in a ("aaa bbb ccc 100 ddd 0"). If so, display a.

Thanks for your help, I've managed to display the whole line but there's still one slight problem. My program's supposed to perform multiple searches but the function I've got only returns the line once and if the user tries to search for another word, it returns nothing.

Here the compilable code:

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

ifstream in;
ofstream out;
const int SIZE = 255;
char a[SIZE];
char b[SIZE];
int i = 0;

void search (char b[]) {
	do
	{
		cin >> b;
		in.getline(a,255);
		for (i=0; i<SIZE+1; i++) {
			a[i] = tolower(a[i]);
			b[i] = tolower(b[i]);
		}
		if (strstr(a,b)!=0){
			cout << "'" << b << "' returned following results" <<endl<<endl;
			cout << a <<endl<<endl;
		}
	} while (!in.eof());
}

int main() 
{
	in.open("test.txt");
	if(in.fail()) {
		cout << "Couldn't open!";
	} 
	search(b);
	in.close();
	return 0;
}

test.txt:

aaa bbb ccc 100 mmm 0
ccc bbb aaa 100 nnn 0
bbb aaa ccc 100 yyy 0

I think I figured that one out.

It requires the file to be reopened at the beginning of the function.

This article has been dead for over six months. Start a new discussion instead.