c++ - 我如何在没有 Stod() 的情况下重写

标签 c++ function compiler-errors

这个问题在这里已经有了答案:





Easiest way to convert int to string in C++

(29 个回答)



Converting Input string to float/double C++

(5 个回答)


4年前关闭。




我怎样才能重写我的阅读详情 不使用 的函数stod() strtod() C++ ?
我将使用的编译器没有启用 c++11,我得到了

'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

最佳答案

使用std::istringstream .

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

编辑 2:对于那些迂腐的人:
下面的示例读取一个 double 数。与上述整数读数非常相似的模式。
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

以上不需要单独的字符串到数字的转换。

关于c++ - 我如何在没有 Stod() 的情况下重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44981107/

相关文章:

c++ - 错误 2296 : '^' : illegal , 左操作数的类型为 'double'

c++ - 将 vector 大小连接到字符串

c++ - Typedef-name 与 C++ 中的 struct 标记冲突

delphi - WMDeviceChange函数调用其他函数/过程时的Delphi Pascal问题

c++ - 用 bool 类型包装返回值

xcode - 在最新的 Xcode 4 中运行旧游戏版本会与 stdio.h 中的 C 函数产生冲突

c++ - 为什么允许将 int 文字设置为指针,但不允许比较?

c++ - 了解具有不同签名的继承和函数

python - 根据输入从函数返回具有特殊行为的列表形式的结果

compiler-errors - 错误: not a valid function argument name