开发者

C++ Weird istringstream behaviour

I apologise for being a C++ novice. I am trying to learn by translating some code from Java.

In this code, the strings that are read in represent letter frequencies in % in a language.

The test string we are dealing with is a10b10c10d10e10f50, as the test code shows.

In the loop below, the first 3 val开发者_C百科ues (0.1, 0,1, 0.1) are correctly read in, as are the 5th and 6th (0.1 and 0.5), but for some reason the 4th value for letter 'd', when i is 9, is read in as 1000000000.0000000, according to the debugger in Visual Studio. Any ideas why?

#include <iostream>
#include <vector>
#include <sstream>
#include <string>
#include <cmath>

using namespace std;

class SymbolFrequency {
public:
    double language(vector <string> frequencies, vector <string> text) {

        for (unsigned int fset = 0; fset < frequencies.size(); fset++) {
            double expected[26];
            fill(expected, expected + 26, 0.0);
            for(unsigned int i = 0; i < frequencies[fset].length(); i += 3) {
                char letter = frequencies[fset][i];
                istringstream is(frequencies[fset].substr(i + 1, i + 3));
                double freq;
                is >> freq; freq /= 100;
                expected[letter - 'a'] = freq;
            }
...

Test code:

int main() {
    SymbolFrequency s;
    const char *fargs[] = {"a10b10c10d10e10f50"};
    vector<string> f(fargs, fargs + 1);
    vector<string> t;
    t.push_back("abcde g");
    double d = s.language(f,t);
    cout << (d) << endl;
    cin.get();
    return 0;
}


You're not calling substr() correctly; try frequencies[fset].substr(i + 1, 2).

(The reason for the strange value is that it parses 10e10 as 100 billion.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜