Reading from file, checking contents of a line

Pages: 12
Hi, I have a file, each line begins with a line number, it looks like this
1
2
3
4
5
1: This is line 1
2: This is line 2
3: This is line 3
etc etc
etc


The user of my program will be specifying a number, I need to read the file in line by line, check for the user given number at the beginning of each line if it matches then i should print the line then exit.

I think ive got the reading the file bit sorted but I dont know how to check the line for the line number

Heres a quick example of what i would do if i were using python
1
2
3
4
list = file.readlines()
string = list[0]
if "1" in string:
    print string

Something like that anyway :),

can anyone shed some light on this for me?

Thanks,

Bodsda
Last edited on
Try something like this:
1
2
3
4
5
6
7
8
9
10
list<string> lines;
string t;
while ( !file.eof() )//read everything in the file
{
   getline(file,t);//store a line in 't'
   lines.push_back( t );//add 't' to the list
}
string first_line = *lines.begin();//get the first element of the list
if ( first_line.find('1')!=string::npos )//check if it has '1'
   cout << first_line;//print it 
Or with vectors ( so you can use subscripting ) :
1
2
3
4
5
6
7
8
9
10
vector<string> lines;
string t;
while ( !file.eof() )
{
   getline(file,t);
   lines.push_back( t );
}
string first_line = lines[0];
if ( first_line.find('1')!=string::npos )
   cout << first_line;

Last edited on
Hi, thanks for your reply. I'm still pretty new to this, so could you please explain what lines 6, 8 and 9 in the first example do please
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
char filename[10];
int number;
printf("Insert number line you want to read");
scanf("%d",&number);
fstream in("filename.txt",ios::in);
if(in.is_open()){
cout<<"";
}
else{
cerr<<"error opening file";
return -1;
}
int counterLine(1);
string what="";
while(getline(in,what))
{
if (counterLine == number)
{
cout<<what<<endl;
}
counterLine++;
}
}
}
sorry the char filename[10] it's useless for your program and instead of cout<<what<<endl; you should write cerr<<what<<endl;
Unfortunately i dont really understand much of that either, sorry, here is what I have so far.

1
2
3
4
5
6
7
8
9
string line;
ifstream alias_in(fullpath.c_str())
                    if(alias_in,is_open())
                    {
                        while(!(alias_in.eof()))
                        {
                            getline(alias_in, line)
                            
                        }


I suppose I would then need an if after the getline, but im still slightly confused how to check a string, would I have to convert it to char then check ch[0]?
If you want to check the value of the 1st character in 'line' you can use line[0]
BTW you are using commas instead of periods ( alias_in.is_open() ) and you need semicolons after lines 2 and 7
I'm fairly new to this as well, i'm having my share of failure with a program which tries to lacoate a certain word in a txt file and get the relative vailue. Anywai the program i posted does the following (the caps lock is meant as explanation, not shouting):
ASK THE USER THE LINE HE IS INTERESTED IN
printf("Insert number line you want to read");
scanf("%d",&number);
OPEN THE FILE AND IF IT DOESN'T EXIST TELLS YOU THAT (it's the same as the first three line you have posted)
fstream in("filename.txt",ios::in);
if(in.is_open()){
cout<<"";
}
else{
cerr<<"error opening file";
return -1;
}
CREATE A COUNTER AND A STRING
int counterLine(1);
string what="";
NOW IN THE FOLLOWING PART IT TAKES THE FILE OPENED AND ASSIGN THE FIRST LINE OF THE FILE TO THE VARIABLE WHAT, ONCE THE CONDITION IS TRUE (THAT IS IF THE COUNTER IS EQUALE TO THE NUMBER OF THE LINE ASKED BY THE USER) IT PRINTS ON VIDEO THAT LINE
while(getline(in,what))
{
if (counterLine == number)
{
cout<<what<<endl;
}
counterLine++;
}
@gaisselick - ah, use the iterations to find what line im on, not actually checking the string, good idea ty :)

@Bazzy -- ooo, thats even easier, il try that, ty

p.s -- yeah i did that quickly and accidentally missed the semi colons and used the comma, cheers
@Bazzy

So ive tried using your idea of line[0] which works great, but i need to be able to compare it.

I need to do something like

1
2
3
if(line[1] != ":")
    cout << line[0] << line[1] << endl;
cout << line[0] << endl;


Without the comparison if a line number is 2 digits then i only get the first digit. But when i try to use that i get an error
 
error: ISO C++ forbids comparison between pointer and integer


How can i get round this?
not sure what you have done with your if condition on line[0]="..."
but i believe you could write something like this
if (line[0]="..." && ( line[1]=":" || line[1]="..." ))
No that error means that i cant compare line[0] to ":" im guessing because of the data types
indeed because it's a string and not an array of charcter, not sure if it would work, but instead of string line you could use char line[20000] (dunno how many but long enough to contain the sentence on the txt file), it might gives you problem with getline. Otherwise you could try my suggestion
Hehe, i tried that and had problems with getline()
if (line[0]="..."&& ( line[1]=":" || line[1]="..." )) is completely wrong! The comparison operator in C++ is == and when comparing characters you need single quotes: if(line[1] != ':')
Ah, brilliant, it now compares that properly.

Sorry to keep asking extra things, but I have another question.

I am now running into the problem of if the user given number is higher then 9 simply comparing user var to line[0] will not work as line 10 would be line[0] = 1, line[1] = 0.

Can anyone think of a more elegant way of achieving my goal of comparing user given number to line number, perhaps taking everything before ':' on the line as an int would be the best solution. How could i do this?
sorry if I posted something completly stupid, btw thanks Bazzy i partially solved a problem i had with my code. Since it's something that Bodsda might wanna do later, i'd like to know if there's a way to skip a certain part of the line you're a getting, i.e.
that's the line i'm retrieving from a file
Isp, M/SEC 43258 32450
now what i'd like to do is to simply get the two sets of numbers, thanks and sorry if I went off topic

@ Bodsda i do not intend to be rude but i believe that if you do it my way you'd get around your problem faster(altought the way you'r doing it is probably gonna be more useful to you in the future), once again sorry if I said something completly stupid but i'm a begginer as I already said
Last edited on
@ gaisselick

Yeah, I think your way will get my problem sorted quicker, I decided to use the other way the first time to actually check the line number in case there were some problems with the text file, which if I use your way it would simply print out the line depending on what line it is on regardless of its line number, which may not be the same (if someone were to edit the text file) but for now I think I am gonna use your way, :P
You can get the 1st number from the line and check it against a numerical value instead of a single character
eg:
1
2
3
4
5
6
7
8
9
10
11
getline(alias_in, line);
stringstream ss ( line );
int line_number;
if ( ss >> line_number )
{
    // now you can check eg if ( line_number == 123 )
}
else
{
   // the line doesn't start with a number
}


http://www.cplusplus.com/forum/articles/6046/
Cheers for that Bazzy,

It sort of works, :) -- I dont think the comparison is working, im using if(ss == argv[(i + 1)]{cout << line << endl;}

but it doesnt seem to be working. heres the code section im using

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
else if(!(strcmp(argv[i], "--lookup")))           // FIXME
            {
                ifstream alias_in(fullpath.c_str());
                string line;
                int line_number;

                if(alias_in.is_open())
                {
                    while(!(alias_in.eof()))
                    {
                        getline(alias_in, line);
                        stringstream ss (line);
                        if(ss >> line_number)
                        {
                            cout << "line: " << line << ", line_number: " << line_number
                                << ", argv[(i + 1)]: " << argv[(i + 1)] << endl;
                            if(ss == argv[(i + 1)])
                                cout << line << endl;
                        }
                    }
                }
                return 0;
            }


I added lines 15 & 16 to make sure that the if(ss >> line_number) was true and it is, heres the output when i run it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bod@bod:~/C++/code/test$ ./cheat.o --lookup 2
line: 1: Test, line_number: 1, argv[(i + 1)]: 2
line: 2: Test, line_number: 2, argv[(i + 1)]: 2
line: 3: Test, line_number: 3, argv[(i + 1)]: 2
line: 4: Test, line_number: 4, argv[(i + 1)]: 2
line: 5: Test, line_number: 5, argv[(i + 1)]: 2
line: 6: Test, line_number: 6, argv[(i + 1)]: 2
line: 7: Test, line_number: 7, argv[(i + 1)]: 2
line: 8: Test, line_number: 8, argv[(i + 1)]: 2
line: 9: Test, line_number: 9, argv[(i + 1)]: 2
line: 10: Test, line_number: 10, argv[(i + 1)]: 2
line: 11: Test, line_number: 11, argv[(i + 1)]: 2
line: 12: Test, line_number: 12, argv[(i + 1)]: 2
line: 13: Test, line_number: 13, argv[(i + 1)]: 2
line: 14: Test, line_number: 14, argv[(i + 1)]: 2
line: 15: Test, line_number: 15, argv[(i + 1)]: 2


Any ideas why the comparison isnt True?
Pages: 12