So me and my groupmates suddenly have some clutchwork at hand. I was assigned of making an import function that reads through a textfile that looks like this, and store it to a 2D array.
Like this http://i.stack.imgur.com/abQ4a.png
The columns are Tab-separated however the difference from that image to mine is that i receive a 3x3 matrix with a blank space substituing one of the numbers and i was wondering how could i detect that blank space
std::ifstream fin("input.txt");
std::string line;
std::getline(fin, line); reads to a new line
std::stringstream iss(line); // puts the line in a stream
std::getline(iss,cell,'\t'); // extracts a string which is tab delimited.
1) If you don't know the size of your data (3x3, 4x4, 5x3) then you want to either use dynamic memory (new/delete) or you want to use std::vector to store the data. Otherwise, if it's always 3x3 you are good with simply making an int[3][3] variable.
2) Whenever you read from the file, check the ifstream .good() function to ensure that you can continue reading from the file.
3) Use std::getline to delimit based on tabs. Use fin >> if you want to convert directly to a number if yoiu don't care about the white space and want to make it a number directly instead of astring first.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main ()
{
std::ifstream fin("input.txt");
std::string line;
std::getline(fin, line);
std::stringstream iss(line); // puts the line in a stream
std::getline(iss,3,'\t');
}
This gives me error :S
Nevertheless my .txt looks like this i.e
1 4 2
3 5
7 8 9
and i have to extract this to a 2d vector even the blank space and susbtitute it later by 0
To use a stringstream you have to #include <sstream> (I think that's its name). Also since you're already using namespace std; there's really no reason to put std:: before everything.
9 IntelliSense: no instance of overloaded function "getline" matches the argument list
argument types are: (std::stringstream, int, char) c:\Users\user\Desktop\ConsoleApplication4\ConsoleApplication4\Source1.cpp 18 1 ConsoleApplication4
And all the elements are separeted by setw(5). What i really wanted was to get the values and get a 2d vector out of it subsituting the blank space for a zero in the vector