call getline() to extract the variables one at a time using the comma as deliminator. There are several ways to do it, here is just one of them.
Note that I did not compile or test the following code
#include <fstream>
#include <string>
using std::string;
using std::ifstream;
int main()
{
string word;
int num;
ifstream in("filename.txt");
while( getline(in,word,',') )
{
num = atoi(word.c_str());
// now do whatever you want with this value
}
}
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
num = atoi(word.c_str());
I realize you didn't compile or test, but atoi() is declared in , and it's in the std namespace. I assume you're using Visual Studio because it's pretty lenient about requiring namespace qualification on the C-inherited library.
On a side note, atoi() is evil. Unless you validate the string first to ensure that it can be represented by int, there's a strong risk of invoking undefined behavior. strtol() is a much better choice because the undefined behavior aspect doesn't existand you have a lot of control over error checking:
const char *src = word.c_str(); // Might be unsafe in the presence of threads
char *end;
errno = 0; // errno is set by strtol() on a range error (for long int)
num = (int)std::strtol(src, &end, 0);
if (end == src || *end != '\0') {
// Length error, bogus characters in the string
}
else if (errno != 0 || !(INT_MIN <= num && num <= INT_MAX)) {
// Range error, valid number but not a valid int
}
else {
// Valid conversion, num contains an int value
}
std::stringstream/boost::lexical_cast are the other common options if you don't like seeing "C code" in a C++ program. ;)
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
(slightly offtopicish) Here 's an article on how well the different methods perform on different compilers
Nick Evan
Not a Llama
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
nice comparisons, but it tests the speed of converting int to std::string, not the other way around. Interesting anyway especially for those who need to optimize their programs.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343