如何使转换功能工作?

How to make conversion function work?

本文关键字:工作 功能 转换 何使      更新时间:2023-10-16

我有一个代码,我正在尝试学习如何在C++中解析。 我理解我所做的一切,但我不明白如何使用atoi(),atof(),strtod()之类的东西。 我知道它应该做什么,但我不明白为什么编译器不喜欢它。 我对错误的关注是"分数[line_count] = strtod (分数);">

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <iomanip>
using namespace std;
int readScores(string inputFile, string name[], float scores[], int     array_size)
{
//delcare variables
ifstream infile;
int line_count = 0;
string line;
string named;
float score;
char character;
int word_index;
string names[array_size];

// open input file
infile.open(inputFile);
//Check if file opens succesfully.
if(infile.fail())
{
cout << "File cannot open!!" << endl;
return -1;
}
while(getline(infile, line))
{
cout << line << endl;
// PARSING GOES HERE
word_index = 0;
for(int i=0; i < (int)line.length(); i++)
{
character = line[i];
if (character == ',')
{
names[line_count] = named;
named = "";
word_index++;
}
else
{
if(word_index == 0)
{
named += character;
}
else if (word_index == 1)
{
score += character;
cout << character << " " << endl;
}
}
}
scores[line_count] =  strtod (score);

line_count++;
}
//close file
infile.close();
//return line count
return line_count;
cout << line_count << endl;
}
int main(void)
{
int array_size = 50;
string inputFile = "Test.txt";
string name [array_size];
float scores [array_size];

readScores(inputFile, name, scores, array_size);
}

函数 strtod() 采用以下形式

double strtod (const char* str, char** endptr);

但你只给它字符串。

如您所见,它需要两个参数,您希望转换为双精度的字符串和"endptr"。endptr 在这里描述为

引用已分配的 char* 类型的对象,其值通过将函数>到数值后面的 str 中的下一个字符来设置。 此参数也可以是空指针,在这种情况下,不使用它。

因此,您需要声明一个 char 指针来保存小数点后的下一个字符,即使不会有一个。这允许您从单个字符串中提取多个双精度,就像分词器一样。

char * endPtr;
scores[line_count] = strtod(score, &endPtr);

编辑

正如 Alex Lop 所指出的,你甚至不是在传递一根绳子给 strtod,而是在传递一个浮点数。看来你想把浮子投成双倍?

当然编译器不喜欢它。请阅读strtod的说明。

Double strtod (const char* str, char** endptr);

string转换为double.

分析 C 字符串str将其内容解释为浮动 点号(根据当前区域设置)并返回其值 作为double.如果 endptr 不是null指针,则该函数还会设置endptr的值指向数字后的第一个字符。

该函数首先丢弃尽可能多的空格字符(如 isspace)根据需要,直到第一个非空格字符 发现。然后,从这个角色开始,取尽可能多的字符 可能遵循类似于浮动的语法有效 点文字(见下文),并将其解释为数值。 指向最后一个有效字符之后字符串其余部分的指针是 存储在endptr指向的对象中。

在你的代码中,你只传递给strtod一个类型为float的参数,并将返回的double结果存储到一个floats的数组中。如果要将float的值从一个变量移动到另一个变量,则不需要任何"转换"函数:

scores[line_count] = score; 

注意:我并没有真正审查您的代码,因为您专门询问了scores[line_count] = strtod (score);。但是在我看了你如何修改score之后,也许它应该是string而不是float的。如果是这样,那么这是要解决的另一点。