Nello
Nello

Reputation: 141

How to read integers and special characters from text file C++

I have this txt file:

{8500, X }
{8600, Y }
{8700, Z }
{8800, [ }
{8900, \ }
{9000, ] }
{9100, ^ }
{9200, _ }
{9300, ` }
{9400, a }
{9500, b }
{9600, c }

This is my code so far:

void file_reader(){

    std::ifstream file("1000Pairs.txt", ifstream::in);
    std::string str; 

    while (std::getline(file, str)){

        !isalpha(c); } ), str.end());
        str.erase(std::remove(str.begin(), str.end(), '{', ',', '}'), str.end());

        cout << str << endl;

        //int_reader(str, array);  // adds the integers to the array
    }       
    file.close(); 
}

Giving an integer, how do I return the corresponding character in C++? Thanks!!!

Upvotes: 0

Views: 1527

Answers (1)

David C. Rankin
David C. Rankin

Reputation: 84642

As mentioned above, by trying to erase, iterate and type-check each of the character is the line, you are making this harder than it needs to be. If your format is as you have shown {num, c }, then you can simplify the read greatly by using a stringstream on line. That way you can just use the normal >> input operators and proper types to read the data you want, and discard the characters you don't, example:

#include <sstream>
...
void file_reader(){
    int num;
    char c;
    ...
    while (std::getline(file, str)){
        char c1, c2;
        std::stringstream s (str);
        s >> c1;                // strip {
        s >> num;               // read num
        s >> c1 >> c2;          // strip ', '
        s >> c;                 // read wanted char
        /* you have 'num' and 'c' - test or map as needed */
        ...
    }
}

You may need to tweak it here or there for your purposes, but this approach is fairly simple and robust. (technically you can check the stream state after each read to check for badbit and failbit, but I'll leave that up to you)

Upvotes: 2

Related Questions