Click here to Skip to main content
15,894,646 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I am trying to code a program that reads a text file line by line. Each line has a single word and we have to sum the ascii values of these words line by line and output it. My text file is:
APPLE
BAGEL
BAGEL
APPLE
APPLE
CRANBERRY
DONUT

And my Code:
C#
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int readFile(){
int sum=0;
ifstream file("text.txt");
string str;
while(getline(file,str)) {
for(int i=0;i<str.length();i++){
    sum=sum+str[i];
    cout<<sum<<endl;
}
sum=0;

}
return 0;
}


int main(){
readFile();

}


When I run this program. the first line of output is correct, after that I don't know what's happening. Also, I don't understand why there are 21 lines of output when it should have only 7? Any feedback would be greatly appreciated. Thanks!

What I have tried:

#include
Posted
Updated 1-Oct-16 12:01pm

Try putting the print statement outside of the for loop. Something like following-
C++
while(getline(file,str)) {
for(int i=0;i<str.length();i++){
    sum=sum+str[i];    
}
cout<<sum<<endl;
sum=0; 
}


Hope, it helps :)
 
Share this answer
 
v4
Quote:
I don't understand why there are 21 lines of output when it should have only 7?

You want 1 sum per word, but your output is in the letter loop so you get 1 output per letter.
Check your counting of output. You claim 21 lines when you have 39 letters.

-----------------
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900