string to int fail :(

Hi!

I try to read some numbers from a file (there're 4 numbers in each lines), which works nicely until i convert string to int. what is wrong with this?
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
27
28
29
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

struct Square{
    int c1;
    int c2;
    int c3;
    int length;
};

void readFile(vector<Square> &kockak){
    ifstream sqr("kocka.txt");
    string numb;
    Square temp;
    stringstream converter;
    while (!sqr.eof()){
        getline(sqr,numb,' '); converter<<numb; converter>>temp.c1;
        getline(sqr,numb,' '); converter<<numb; converter>>temp.c2;
        getline(sqr,numb,' '); converter<<numb; converter>>temp.c3;
        getline(sqr,numb); converter<<numb; converter>>temp.length;
        kockak.push_back(temp);
    }
    sqr.close();
}
Last edited on
what makes you think that there's something wrong?
i printed out temp after each lines and those weren't the numbers I wanted them to be:) e.g: the second number in the file is 4, but temp.c2 becomes 0. I know, it's a beautiful number, but 4 would be better:)

input:
3 4 5 10
-1 2 6 67
3 4 5 6

output:
3 0 2 2686600
3 0 2 2686600
3 0 2 2686600
Last edited on
the problem is that converter encounters an error (eof) while converting numb to temp.c1. After that it doesn't do anything anymore.

why don't you use the operator>> directly?
oh my:) i have no idea why i made it this difficult... thank you very much! :)))
try somthing more simple. Heres what I use, it's templated so you don't have to write one for EVERY CONVERSION...

template<class type1, class type2>
type2 conv(const type1& t1)
{
stringstream ss;
type2 t2();
ss<< t1;
ss>> t2;
return t2;
}

1
2
3
4
//using it:
int i = conv<string, int>(string("5"));
//or mabey...
string s = conv<long double, string>((5 * PI));


Topic archived. No new replies allowed.