C++ c++;从字符串中提取数字并求和

C++ c++;从字符串中提取数字并求和,c++,C++,大家好,我在.txt中有一组数据,在字符串之间包含正负数字,并带有“:“as delimeter。如何提取负数并将其相加以显示。我尝试使用substr,但位置不固定 文本文件: tom12:Phone Bill:-45.90:12JAN14 tom12:Utility Bill:-133.50:17JAN15 tom12:Housing Bill:-200.78:01JAN15 tom12:Salary:2700.00:02FEB15 tom12:Miscellaneous:-30.52:20J

大家好,我在.txt中有一组数据,在字符串之间包含正负数字,并带有
“:“as delimeter
。如何提取负数并将其相加以显示。我尝试使用substr,但位置不固定

文本文件:

tom12:Phone Bill:-45.90:12JAN14
tom12:Utility Bill:-133.50:17JAN15
tom12:Housing Bill:-200.78:01JAN15
tom12:Salary:2700.00:02FEB15
tom12:Miscellaneous:-30.52:20JAN15
tom12:Child Needs:-80.95:15JAN15

对不起,也许我的qn不清楚。我想读每一行,得到字符串中的双精度(-45.00,-133.50,-200.702700.00,-30.522,-80.95)并将所有负数加起来(-491.65),然后使用工资减去余额(2700-491.65=2208.35)希望这是清楚的,希望这能对你有所帮助

std::ifstream file("your_file");
std::string   line;
int totalNegative = 0;
int totalPositive = 0;
while(std::getline(file, line))
{
   std::stringstream   linestream(line);
   std::string         data1;
   std::string         data2;
   int                 val3;
   std::string         data4;//If you want fourth string you can use.

   getline(linestream, data1, ':');//Getting tom12
   getline(linestream, data2, ':');//Getting Phone Bill
   // Read the integers using the operator >>
   linestream >>val3;

   if(val3 > 0)
      totalPositive += val3;
   else
      totalNegative += val3;
}
cout <<Difference is " << (totalPositive-totalNegative);
std::ifstream文件(“您的_文件”);
std::字符串行;
整数负=0;
int TOTAL正=0;
while(std::getline(文件,行))
{
std::stringstream linestream(行);
std::字符串数据1;
std::字符串数据2;
int val3;
std::string data4;//如果需要第四个字符串,可以使用。
getline(linestream,data1,':');//获取tom12
getline(linestream,data2,':');//获取电话账单
//使用运算符读取整数>>
linestream>>val3;
如果(val3>0)
总正+=val3;
其他的
总负+=val3;
}

你不知道到目前为止你都试了些什么吗?此外,您还可以使用getline获取每行的第三部分,然后将其转换为整数,然后对其求和。具体来说,您要求和的数字是什么?编辑你的帖子并用粗体显示。有人回答了我的问题,现在不见了。为什么?谢谢,我不知道在getline中可以使用分隔符。但是我不懂这行std::stringstream linestream(line);我更新了答案。如果对你有帮助的话,请注明答案和帮助。很抱歉,我的数据是double而不是int,当我将val3改为double并编译时,它们都不计入小数。当我尝试打印时,它们只打印数据1和数据2。库特