chars and their order

Mar 29, 2014 at 11:42pm
how can you pull in a single char from a file and then figure out what number it is in the alphabet and in the word?

Mar 30, 2014 at 12:00am
how can you pull in a single char from a file

There is a handy-dandy get() function that retrieves one character. You don't have to retrieve just one character, though. You could just grab and process whole lines.

what number it is in the alphabet

All chars have a unique "ASCII" code. Finding out what number it is in the alphabet is as simple as ch - 'A' + 1 (remember to use toupper or tolower, so you don't have to care about the case).
http://www.asciitable.com/

what number it is ... in the word

Assuming you have retrieved the word itself, I think this should be very simple.
Last edited on Mar 30, 2014 at 12:01am
Mar 30, 2014 at 12:08am
how can you process the entire word?
Mar 30, 2014 at 12:13am
Just like you would get a word from the user. C++ file streams are designed to be used just like what you use for console input/output.

Here's an analogy between console I/O and file I/O:
1
2
3
4
5
//Console
char ch = cin.get(); //Grab one character
string s;
cin >> s; //Grab a word
getline(cin, s); //Grab a line 

1
2
3
4
5
6
7
8
9
10
11
//Files
ifstream file("File.txt");
if(!file.is_open()){
    cout << "Bad file path.";
    return -1;
}

char ch = file.get(); //Grab one character
string s;
file >> s; //Grab a word
getline(file, s); //Grab a line 


Almost exactly the same.

Edit:
Sorry, misread your post.
I am assuming you are using std::string to store your word. So, for example, for finding out the number in the alphabet a letter is for each word, you'll probably iterate over the string:
1
2
3
4
5
6
7
//Have a function to tell you the number given a letter
unsigned short int alphabet_position(char ch){
    ::tolower(ch);
    if(ch < 'a' || ch > 'z') //Means ch is not an English letter
        return 0;
   //Find out the position and return it
}

Then in your code, you might have something like this:
1
2
3
4
std::string word("");
file >> word;
for(std::size_t I(0); I < word.size(); ++I)
    /*Find out the corresponding number for each character in word and do something with it*/
Last edited on Mar 30, 2014 at 1:44am
Topic archived. No new replies allowed.