为什么我的程序将实数视为字符串?

问题描述 投票:0回答:1

我是一名 C++ 初学者,正在尝试编写一个程序,将可变数量的值写入文件,然后对它们求和并显示总数。但是,我的程序不是对这些值求和,而是将它们视为字符串并附加它们。有人有什么建议吗?

我的完整代码: `#include #包括 使用命名空间 std;

 void createValuesFile();
 void calculateTotalValue();
 
 int counter = 0;
 
 int main()
 {
      createValuesFile();
      calculateTotalValue();
 }

 void createValuesFile()
 {
      //Declare an internal name for an output file.
      ofstream valuesFile;
      
      //Declare a variable to store the number of values.
      int valueAmount = 0;
      
      double enteredValue = 0;
      
      //Ask how many values there are.
      cout << "How many values are there?\n";
      cin >> valueAmount;
      
      //Open a file named values.dat on the disk.
      valuesFile.open("values.dat");
      
      //Determine if the file was opened.
      if (!valuesFile.is_open())
      {
           "\nUnable to open a file!\n";
      }
      else
      {
           //Write values to the file.
           for (counter = 1; counter <= valueAmount; counter++)
           {
                cout << "Enter value number " << counter << ".\n";
                cin >> enteredValue;
                valuesFile << enteredValue;
           }
           
           //Close the file.
           valuesFile.close();
      }
 }

 void calculateTotalValue()
 {
      //Declare an internal name for an input file.
      ifstream valuesFile;
      
      //Declare a variable to hold the values that will be combined.
      double currentValue = 0;
      
      //Declare a variable to hold the total value.
      double totalValue = 0;
      
      //Open a file named values.dat on the disk.
      valuesFile.open("values.dat");
      
      //Determine if the file was opened.
      if (!valuesFile.is_open())
      {
           "\nUnable to open a file!\n";
      }
      else
      {
           //Calculate the total value.
           while (!valuesFile.eof())
           {
                valuesFile >> currentValue;
                totalValue = totalValue + currentValue;
           }
      
      //Display the total value.
      cout << "The total value is " << totalValue << ".";/
      
      //Close the file.
      valuesFile.close();
      }
 }`
c++ file variables addition
1个回答
0
投票

主要问题是您将值写入文件时没有使用空格分隔符,因此写入文件的只是一个大数字。

我建议在每个值的末尾添加一个

'\n'

valuesFile << enteredValue << '\n';
//                         ^^^^^^^
© www.soinside.com 2019 - 2024. All rights reserved.