First off, hello all. I am new to the forum, but I have recently been using the site for advice. I am currently a novice at C++, so please forgive my ignorance.
Question: I am attempting to read two different lines from a .txt file, and I thought I could get away with running two IF statements in order to get the lines at the same time. Is is possible to do this? If not, is there a better way to go about doing this?
The result of the code below is that it reads the first string (str), but does not read the second IF all together, thus not grabbing my second string (str2).
Once you call getline() or any other read operation on a file, an internal pointer of the fstream class is incremented, and the next read starts at that point. What is happening in your program is that in your first loop you've already read 35000 lines of your file, and your second for loop starts reading at line 35001. You will get the result you want putting both statements in a single loop:
It is possible to read two lines at the same time, but it's not what you want. It would not work as you intend to.
What are you aiming to achieve? If you want to compare two lines, simply load first line, then second line, and then compare them.
If you plan on doing other thing, you may want to tell us what is your point, and we will provide you with some way of achieving your goal.
Combining the two statements into the single FOR loop solved it.
I originally learned that its better to use separate loop statements because its "easier to read", but as I progress through C++, I'm learning that this isn't the best way to go about it.
The whole purpose of the program is to grab these strings from a .txt file, convert them to double's, and then do a subtraction between them. I shall continue my research in converting char types...
So you can do it one by one - you don't have to use both at once :)
Remember, that if your file is written properly, you can use >> operator to get formatted input from ifstream, so all in all it would just look like this
1 2 3 4 5
ifstream file;
int number;
//code...
file >> number;//Load formatted input from file to number
//That's it! Number is already an integer, no need to do anything else, no conversions or anything.