我正在从文本文件中读取值并将其作为字符串打印到屏幕。我们的想法是读取每个单独的字符串并将它们打印到屏幕上,并在其旁边打印读取的字符串的运行平均值。 我有我的字符串浮动声明
int main()
{
string inputfile, intstring;
float counter;
counter = 0;
float average;
average = 0;
float stringconv = stof(intstring);
cout << "Enter the name of a file to open\n";
cin >> inputfile;
ifstream inFile;
inFile.open(inputfile.c_str());
以后再计算平均值
while (!inFile.eof())
{
getline(inFile, intstring, ' ');
cout << intstring <<","<<average<< endl;
//increments counter to keep average output correct
counter = counter +1;
//goes to next line at each space encountered in text file
average = (counter + stringconv) /2;
}
我已经把这包括在内,万一我的问题就在那里。谁能告诉我如何正确宣布我的转换? 这是一个完整的版本,编译
#include <math.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string inputfile, intstring;
float counter;
counter = 0;
float average;
average = 0;
float dividor;
dividor = 1;
cout << "Enter the name of a file to open\n";
cin >> inputfile;
ifstream inFile;
inFile.open(inputfile.c_str());
if (!inFile)
{
cout << "Error opening file " << inputfile << endl;
char stopchar;
cin >> stopchar;
return -1;
}
while (!inFile.eof())
{
//goes to next line at each space encountered in text file
getline(inFile, intstring, ' ');
cout << intstring <<","<<average<< endl;
float stringconv;
stringconv = stof(intstring);
average = (counter + stringconv)/dividor ;
dividor = dividor +1;
//increments counter to keep average output correct
}
inFile.close();
char stopchar;
cin >> stopchar;
}
答案 0 :(得分:1)
下面:
string inputfile, intstring;
...
float stringconv = stof(intstring);
你不能这样做。我的意思是,你可以,但它并没有做你认为它做的事情。您认为自己正在创建宏或功能,以便您可以更改intstring
,然后stringconv
会自动更改。但你实际上做的是将未初始化的字符串转换为整数一次,并且永远不会再次更改它。您必须在读取循环内进行转换。
编辑:如果您不需要使用stof()
,那么您可以使用流输入运算符来节省很多麻烦:
float number;
inFile >> number; // this is the basic form
while(inFile >> number) // this is how to do it as a loop
...
答案 1 :(得分:0)
在C ++中,float stringconv = stof(intstring);
赢得了Verilog中的assign
自动转换功能。
每次需要转换时,请致电stof()
。
试试这个:
while (!inFile.eof())
{
getline(inFile, intstring, ' ');
cout << intstring <<","<<average<< endl;
//increments counter to keep average output correct
counter = counter +1;
//goes to next line at each space encountered in text file
stringconv = stof(intstring); // add this here
average = (counter + stringconv) /2;
}