如何使转换功能工作?
How to make conversion function work?
我有一个代码,我正在尝试学习如何在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
结果存储到一个float
s的数组中。如果要将float
的值从一个变量移动到另一个变量,则不需要任何"转换"函数:
scores[line_count] = score;
注意:我并没有真正审查您的代码,因为您专门询问了scores[line_count] = strtod (score);
。但是在我看了你如何修改score
之后,也许它应该是string
而不是float
的。如果是这样,那么这是要解决的另一点。
- OpenSSL 解密功能无法正常工作
- 链表中的显示功能无法正常工作
- 打印功能无法正常工作 - 链表
- 排序功能在C++中未按预期工作
- 如何组织 git 工作流以修复错误并同时引入新功能
- 为什么必须动态分配扩展数组才能使此功能正常工作C++
- Qt C++括号匹配和突出显示当前线路功能无法协同工作
- 下面的代码是如何工作的?它输出分解的数字并且功能齐全,我只是不明白它是如何做到的
- C 功能如何内部工作
- 大写功能无法正常工作
- 为什么这个base64解码/编码功能不能正常工作?
- 如何使功能"run"工作。程序在调用运行时退出
- C 11螺纹 - 非静态成员功能的使用无效 - 工作GCC 5.1.0损坏的GCC 7.3.1
- Lower_bound功能无法正常工作
- 仅一个功能的链接错误.在同一类和CPP文件中具有相似签名的其他函数工作正常
- 功能测试宏在 Visual C++ 中无法正常工作
- 将Linux打开,读,写,关闭功能以在Windows上工作
- 如何使用字符串更改此插入功能以在链接列表中工作
- 澄清功能如何工作并与类相关
- C //尝试重写一个工作代码以包括我的功能