How do you getline a float or int?

Simple question.
How do you getline a float or integer?

I need to record the information.
Thank you!!!
"How do you getline a float or integer?" Do you mean from a file? Well if you want to read data from a file you just use
1
2
3
ifstream read(randomnamehere);
......
read>>data;

Where ofcourse data is int or float. I don't know if this is what you need but please feel free to post your questions and I will try to help you. Happy coding : )
You mean "How do I convert numeric input into a number and store it?"

maybe like that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
template <typename T>
inline T ToNumber(const string& text)
{
	std::stringstream ss(text);
	T result;
	ss >> result;
	return result;
}

template<typename T>
vector<T> Function(const char* file)
{
        string buffer;
	ifstream input(file, ios::in);
        vector<T> vec;

	if (!input.is_open())
		throw;

	while(input.good())
	{
		getline(input, buffer);
                vec.push_back(ToNumber<T>(buffer);
        }
        return vec;
}
@codekiddy
In your ToNumber function - how do you tell that the returned number is valid and not the unitialised garbage value.
guestgulkan,
I copied this code from my projet and don't have to check whether input is number or not because *.dat file from which I read is created by the same program which writes ONLY numerical information out to the file.


If OP has problem with that then this is better one:

1
2
3
4
5
6
7
template <typename T>
inline T ToNumber(const string& text)
{
	std::stringstream ss(text);
	T result;
	return ss >> result ? result : 0;
}


EDIT:

The same result and side behaviour is achived by using atoi function, but it is not template and works on integral values, and because OP asked for generics I gave him a template :)
Last edited on
Topic archived. No new replies allowed.