如何对给定文件中字符串的ascii值求和 [英] How do I sum the ascii values of a string in a given file

查看:363
本文介绍了如何对给定文件中字符串的ascii值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我正在尝试编写一个逐行读取文本文件的程序。每行都有一个单词,我们必须逐行将这些单词的ascii值相加并输出。我的文字文件是:

APPLE

BAGEL

BAGEL

APPLE

APPLE

CRANBERRY

DONUT



我的代码:

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:

#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();

}





运行此程序时。第一行输出是正确的,之后我不知道发生了什么。另外,我不明白为什么有21行输出时应该只有7?任何反馈将不胜感激。谢谢!



我尝试了什么:



#include



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

推荐答案

尝试将print语句放在for循环之外。类似于以下内容 -

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





希望,它有帮助:)



Hope, it helps :)


引用:

我不明白为什么有21行输出它应该只有7?

I don't understand why there are 21 lines of output when it should have only 7?



你想要的每个单词1个总和,但你的输出是在字母循环中,所以每个字母得到1个输出。

检查你的输出计数。当你有39个字母时,你要求21行。



-----------------

您应该尽快学会使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - A初学者指南 [ ^ ]



调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。 />
当代码不做ex的时候你已经接近了一个错误。


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.


这篇关于如何对给定文件中字符串的ascii值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆