I am trying to recreate a program I did in school 10 years ago, which was the last time I did programming, and I am failing at the very first lines of code.
The program was made to create a sort of language/translator:
int letter;
A = 1
B = 2
C = 3
...
Z = 26
Equation = letter - letter - letter ...
Then I had a .txt file with over 3000 words (one on each line \n). The program would take the first word and go through each letter and give it a number. For examplem, the word "Banana" would be:
2-1-19-1-19-1 = -39
The program would then write: "= -39" after that word in the .txt file and carry on with the next word.
I hope you understood the function of my program; a fun project I need great help with.
I need help with the .txt reading and equation (the whole code for it):
Read first word in the pre.txt --> asign numbers to the letters of the first word --> execute math equation --> take answer and save in post.txt --> repeat.
Here is a C code that does what you ask for. But it only trigger lower case letters and not all of them. You can modify it to accept all alphabet letters or even symbols if you want to add them as well and accept both lower and upper case letters but it will need more code. I will let you figure that out.
#include <iostream>
#include <string>
#include <cctype>
#include <fstream>
int char_to_int( char c ) // 'A' == 1, 'B' == 2 etc.
{
// in our alphabet, 'A' is at position 1, 'B' at position 2 etc
staticconst std::string alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
// locate the position of this character in the alphabet
constauto pos = alphabet.find( std::toupper(c) ) ;
// return zero for characters that are not in our alphabet
return pos != std::string::npos ? pos : 0 ;
}
int word_to_int( const std::string& word )
{
if( word.empty() ) return 0 ;
int number = char_to_int( word[0] ) ;
for( std::size_t i = 1 ; i < word.size() ; ++i ) number -= char_to_int( word[i] ) ;
return number ;
}
int main()
{
std::ifstream in_file( "pre.txt" ) ;
std::ofstream out_file( "post.txt" ) ;
std::string word ;
while( in_file >> word ) out_file << word << ' ' << word_to_int(word) << '\n' ;
}