I am reading a file in the format of:
"i10 i20 i30 d40 d50 i60 i70 i80"
I need to seperate the chars 'i' and 'd' from the int values, so I can use the chars to tell me what should be done with the int values. I have been able to do this using the getline() function and iterating through testing every value. However, I was told there was a better way to do this using the format:
while(inf >> command >> value){
..
}
I haven't been able to get this to work. I can only get it to do the while loop when I remove the value portion( while(inf >> command) ).
Here is what I have so far:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char command;
int value;
ifstream inf;
inf.open("File1.dat", ifstream::in);
if(!inf.is_open())
{
cout << "Failed to open file." << endl;
}
while(inf >> command >> value) { //Information in loop is for testing if loop is running
/*if (command == 'i')
cout << command;
else {
cout << 0;
}*/
cout << "Loop running";
}
inf.close();
return 0;
}
Umm... Is your data supposed to be formatted like that? At first your letters ('i' and 'd') are at the beginning of the numbers, but then 60 has an 'i' at the start and the end, and 70 has the 'i' at its end, and 80 has no 'i' or 'd'. I'm assuming it's just a small typo, but I want to make sure before I try anything, 'cause if it's not a typo that changes things.
hmm. cornstalks, your code works for me too. I looked in my data file and found that there is some text in the first line before it starts listing the 'i's, 'd's and ints. So I typed a bunch of random letters into your code like so: [color=#008800]"testing afdsfasdfgwagsd i10 i20 i30 d40 d50 i60 i70 i80" and it no longer works. I guess that is my problem. Thank you.
edit: just used the inf.ignore() function to ignore the first line of the data file and it all works fine now.
Yes, additional text that breaks the formatting convention at the beginning of the file would cause the while loop to evaluate to false. Essentially, when you try to parse the int, the ifstream just sees text and no int, so it fails. Skipping the text is the right idea.
@TheTroll: That's great and all, but... the last time I checked ifstream was C++, not C#. That, and I think "splitparam" should be "trimparam", the program parses strings and not ints, and the command is not parsed.