-
January 26th, 2010, 04:51 PM
#1
Getline_input_to_int
Hello,
Is it possible to convert the input you get from using the getline(inputfile, string) to an int?
Say i have a file "abcd.txt", with the following content:
6
3
How can i convert the 6 and 3, which are strings because of the getline() function, to an integer?
Thank you very much,
Neil.
-
January 26th, 2010, 04:55 PM
#2
Re: Getline_input_to_int
There are many ways to convert a string to an int. Some may be better than others for various situations:
sscanf()
istringstream
strtol()
atoi()
boost::lexical_cast
to name just a few.
-
January 26th, 2010, 05:03 PM
#3
Re: Getline_input_to_int
Thanks for your quick reply, i get an error whilst compiling though.
Heres my code:
<code>
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
ifstream diagram;
diagram.open("diagram.in");
string line;
int one;
int two;
getline(diagram, line);
one = atoi(line);
getline(diagram, line);
two = atoi(line);
system("PAUSE");
return 0;
}
</code>
The error i get is the following: error C2664: 'atoi' : cannot convert parameter 1 from 'std::string' to 'const char *'
- Neil.
-
January 26th, 2010, 05:19 PM
#4
Re: Getline_input_to_int
Yes, atoi() is a C function, so it doesn't know about std::string. The error is telling you exactly what's wrong. You'll need to use std::string's compatibility method, c_str().
-
January 26th, 2010, 05:27 PM
#5
Re: Getline_input_to_int
Are there other chars on each line besides what you have shown ?
if not, whu not read directly into an int variable ?
-
January 26th, 2010, 05:29 PM
#6
Re: Getline_input_to_int
Thank you, Lindley. That helped!
@ Philip, is there a way i can read it directly into int?
- Neil.
-
January 26th, 2010, 06:10 PM
#7
Re: Getline_input_to_int
Code:
int one , two;
diagram >> one >> two;
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|