hi, my file say ll.out having data like 12.0 , -25.30, 0,0,....etc
i want to store data in a variable one by one say var=12.0 now i want to compare this value with zero.if var !=0 then want to store those values into a array. here i want to assign data from file to var every time. can anybody help me. thank you

Recommended Answers

All 4 Replies

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
    }
}
num = atoi(word.c_str());

I realize you didn't compile or test, but atoi() is declared in <cstdlib>, 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 exist and 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. ;)

(slightly offtopicish) Here's an article on how well the different methods perform on different compilers

commented: nice. +5

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.