Hello, so I have a program that's not doing what I want it to do. This is the assignment:
The nth term of the sequence of triangle numbers is given by, tn = 1/2 n (n+1); so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55,...
By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.
the 'words.txt' has a bunch of words in this format:
"ABSTRACT"
"YOUTH"
there's about 1000 words in that format.
And for any triangle words I find, I put it into another text file which I called triangle.txt.
Now for my program, it pulls the 'words.txt' file just fine but it doesn't recognize any of the words in the file as triangle words.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cmath>
#include <cstdlib>
int getCharValue(char a);
double sum1(std::string name);
int main() {
int a[500];
int n;
int t = 0;
std::string value[500];
std::string words;
std::string word[500];
int count = 0;
std::ifstream fread;
std::ofstream fwrite;
std::cout << std::endl;
int i = 0;
char c[50];
fread.open("words.txt");
fwrite.open("triangle.txt");
if (!fread.is_open())
std::cout << "Unable to open a file." << std::endl;
if (!fwrite.is_open())
std::cout << "Unable to open a file." << std::endl;
while (fread.good())
{
getline(fread, words, ' ');
if (words != "")
{
word[i] = words;
std::cout << words << std::endl;
double wordsum = (sqrt(1 + 8 * sum1(word[i])) - 1.0) / 2.0;
if (wordsum == (int) wordsum)
{
fwrite << words;
fwrite << "\n";
count++;
}
i++;
}
}
std::cout << "Total triangle words are: " << count++ << std::endl;
fread.close();
fwrite.close();
system("pause");
return 0;
}
double sum1(std::string name){
int result = 0;
for (int i = 0; i < name.length(); i++)
{
result += (int) name[i] - 64;
}
return result;
}
|