简体   繁体   中英

C++ sum of digits of each element in a column

I am new to C++, trying to import dates into a program, adding up digits of day, month, year resp and writing back to txt.

input data

  sl.no   name  day month year
   1       Rob   15  05   2019
   2       Tim   12  06   2002  

Desired output data in txt

  sl.no   name     day      month   year
   1       Rob       6         5      3
   2       Tim       3         6      4

I have been able to import data from a txt file and also add the digits in day but it does not repeat forward. what am i doing wrong ?

sample code

    #include <iostream>
    #include <fstream>
    using namespace std;

    int main()
    {
    ifstream theFile("data.txt");
    int id,day,month,year,daysum=0,monthsum=0, yearsum=0;
    string name;

    while (theFile >> id >> name >> day >> month >> year)
    {
    cout << id << ", "<< name <<", "<< day<<", "<<month <<", "<< year<<","<< endl;
    }

    while (day > 0)
    {
    daysum = daysum + (day % 10);
    day = day / 10;
    cout << daysum << endl;
    }

you are reading the file and data wrong, you need to discard the header (sl.no name day month year)

and then accumulate the daysum while reading the file progressively one row after the other until the end...

I am no expert . but have been in your spot a few months ago.. break down the problem into smaller steps..

My approach..

Pseudo Code:

  1. Ditch the header
  2. Create a function for adding the digits
  3. Read data from file
  4. Use a loop to run through each element of the every column and use the function created
  5. Store results in a variable
  6. Output variable to a new text file

comment if there is a specific area where you are stuck..

Try this to reduce it to single digits.. knit to other parts of your code..


   #include <iostream>
  
   using namespace std;
   
   int main()
   {
       
       long long num;
   
       cout << "Enter a number: ";
   
       cin >> num;
   
       int sum = 0;
   
       while (1)
       {
           sum += (num % 10);
   
           num /= 10;
   
           
           if (0 == num)
           {
                
               if (sum > 9)
               {
                   num = sum;
   
                   sum = 0;
               }
               else
               {
                   cout << "Answer: ";
   
                   cout << sum << endl;
   
                   return 0;
               }
           }
       };
   
       return 0;
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM