reading

If for instance I have a text file that contain the data below. Here I call it as mytextfile.

2
1234567894 99.0
1234567898 88.0

I want to read the very first line in the text file. This is how I do it, but apparently this code does not working. Can you tell me what is wrong with it?

while (is.good())
{
d=are.get();
if(d== i)
i++;
}
is.close();
cout<< i << endl;

i here is the number in the first line. I have initialise i=1 and when I run this particular code, cout i will be give the value that I initialise earlier. Why is that?
For this to work "are" has to be the name of the variable that you associated with the input file stream. I can't follow your code because of the names you have given your variables.

Naming variables after obscure articles in the english language of all things is a great way to confuse yourself and anyone trying to read your code.
aaa I am sorry, I forgot to change the is.good(). It suppose to be are.good(). Anyway I have try it by naming it to are.good, but it still give me the value that I have initialise earlier which is i=1

and I have already change the is.close to are.close
Last edited on
Both 'i' and 'd' are cast as integers right?
No.. I declare my d as char. While i, I declare it as an integer. Is that what I where went wrong?
Yup. They are seperate values my friend! Don't worry that's a pretty easy mistake to make.
Thanks for pointing that out. However, for this line in the code cout <<i << endl, it still give i as the value that I initialise earlier.
Can I see more of your code? If you want to copy\paste the whole thing that should be fine.
Here it is.. actually the whole code is in one function.


int i=1;
char c;
int d;
int num=0;
ifstream is; //read
ifstream are; //read
ofstream bFile; //write

is.open("mytextfile.txt");

while (is.good()) // read the many line in the text file
{
c=is.get();
if(c=='\n')
num++;
}
is.close();
cout<<"number of lines in file is "<<num<<endl;

are.open("mytextfile.txt");
while (are.good())
{
d=are.get();
if(d== i)
i++;
}
are.close();
cout<< i << endl;


if(num<5) // write to the end of the list of data
{
if(i<5)
{
bFile.open("mytextfile.txt",ios::in|ios::out);
i++;
bFile << i << endl;
bFile.close();
}

bFile.open("mytextfile.txt",ios::app);
bFile << student::getReg() << " " << fixed << setprecision(1) << student::getMark() << " " << endl;
bFile.close();

}
Last edited on
You see where you're trying to test for '\r'? That's two characters, you would need to read in a char, test to see if it's a '\' then read in the next char and process it accordingly. You cannot tell it to get one char and expect it to process two.
Sorry.. I already edit that part in my previous post. it suppose to be if(d==i) not if (d=='/r')

I am so sorry about that.
Topic archived. No new replies allowed.