2017-07-07 41 views
-3

我如何重寫我的readDetails功能,而無需使用STOD()關於strtod()C++? 我將使用的編譯器沒有C++ 11啓用,我得到我怎麼可以重寫沒有STOD()

「STOD」在此範圍錯誤

int readDetails(SmallRestaurant sr[]) 
{ 
//Declaration 
ifstream inf; 

//Open file 
inf.open("pop_density.txt"); 

//Check condition 
if (!inf) 
{ 
    //Display 
    cout << "Input file is not found!" << endl; 

    //Pause 
    system("pause"); 

    //Exit on failure 
    exit(EXIT_FAILURE); 
} 

//Declarations and initializations 
string fLine; 
int counter = 0; 
int loc = -1; 

//Read 
getline(inf, fLine); 

//Loop 
while (inf) 
{ 
    //File read 
    loc = fLine.find('|'); 
    sr[counter].nameInFile = fLine.substr(0, loc); 
    fLine = fLine.substr(loc + 1); 
    loc = fLine.find('|'); 
    sr[counter].areaInFile = stod(fLine.substr(0, loc)); //line using stod 
    fLine = fLine.substr(loc + 1); 
    loc = fLine.find('|'); 
    sr[counter].popInFile = stoi(fLine.substr(0, loc)); 
    fLine = fLine.substr(loc + 1); 
    sr[counter].densityInFile = stod(fLine); //line using stod 
    counter++; 
    getline(inf, fLine); 
} 

//Return 
return counter; 
} 

以下未聲明是我想讀的文本:

人口普查區201,奧陶加縣,阿拉巴馬州| 9.84473419420788 | 1808 | 183.651479494869 人口普查區202,奧陶加縣,阿拉巴馬州| 3.34583234555866 | 2355 | 703.860730836106 人口普查區203,奧陶加縣,阿拉巴馬州| 5.35750339330735 | 3057 | 570.60159846447

回答

0

使用std::istringstream

std::string number_as_text("123"); 
int value; 
std::istringstream number_stream(number_as_text); 
number_stream >> value; 

編輯2:對於那些迂腐的人:
下面的例子讀取雙。與上述整數讀數非常相似的模式。

std::string number_as_text("3.14159"); 
double pi; 
std::istringstream number_stream(number_as_text); 
number_stream >> pi; 

您還可以使用sprintf的變種。

編輯1:另一種解析方法
你可以嘗試:

std::string tract; 
std::string county; 
std::string state; 
double value1; 
char separator; 

//... 
std::ifstream input("myfile.txt"); 
//... 
std::getline(input, tract, ','); 
std::getline(input, county, ','); 
std::getline(input, state, '|'); 
input >> value1; 
input >> separator; 
//... 
input.ignore(100000, '\n'); // Ignore any remaining characters on the line 

以上不需要單獨的串號的轉換。

+1

來吧,這甚至不是他們要求的轉換。另外,這顯然是一些愚蠢的。 –

+1

@BaummitAugen:他們詢問將字符串轉換爲十進制(數字),這是'std :: istringstream'的作用。 –

+0

@BaummitAugen:關於如何閱讀文件有很多帖子,但它們都略有不同。這個有'|'作爲分隔符以及','。 –

相關問題