Reading comma-separated data from file
Hi,
I am just starting with C++ and want to write a small program that reads data from a file and calculated some numbers from it. The second part has been done, but I got stuck with the file reading. Actually, I can read the file, but I don't manage to get the data into matrix variables. The format op the file is: 1,1020 2,5630 3,889 etc. Can anyone help me with this? Thanks in advance MeL |
Read lines of file into variable line.
Code:
int num, next_num; |
Thanks for your help. If I understand this correctly, this command extracts the values that are separated by the colon. These values are extracted from the string 'line'. So how do I get one line from a file in the variable 'line'?
MeL |
File Format:
3456, 1346, 1784, 45667, Function to read it: int i, lines[numlines]; //array FILE *fileHandle; //file pointer fileHandle = fopen("filename", "rb"); //open filename as read binary if (!fileHandle) return 0; //file didn't get opened so return for (i=0; i < numlines; i++) fscanf(fileHandle, "%d,\n", &lines[i]); return 1; There! Now if you want to access line 1 you would just: line[0], or line two: line[1] I didn't put much error checking into it, and it isn't very dynamic, but you should be able to figure that out (although it sounds like your a new programmer, forgive me if this is an incorect assumtion). |
Yes, I am indeed a :newbie: in C++ programming. But you have to start once :) I want to perform some calculations on a file with the following format:
1,362 2,323 3,341 4,1339 5,1103 6,1248 7,1159 8,1160 9,1089 10,1183 11,1171 12,994 etc. The file is generated on another system by a program that I do not control, so I have to deal with it. By reading some manuals, this is what I could do to open the file and display it (see below). I tried all the suggestions above, but they don' work with this file. I want the values to go into an array. The number before the comma is the number in the array. So A[1]=362, A[2]=323, etc thanks in advance for all your help. MeL ---> read and display ifstream OpenFile("test2.txt"); char ch; while(!OpenFile.eof()) { OpenFile.get(ch); cout << ch; } OpenFile.close(); --> an option to read a full line and separate values by comma (does not work) ifstream infile("test2.txt"); while(!infile.eof()) { infile.getline(line, 40, endl); /* line ends after 40 characters of 'end of line' */ std::cout << "Number " << line << std::endl; } |
All times are GMT -5. The time now is 08:14 AM. |