Search code examples
c++ioifstream

Reading space seperated txt file into arrays C++


the problem that I am having is that I should read in the values 7 write 0x01 0x27 from my .txt file and the loop will only run 1 time, giving the output 0 - 7 1 0x01 0x27 (the 1 represents write, 0 = read, 2 = not set), but, the values that I have printed out with the print statement show the values as

0 - 7 1 0x30 0x78
1 - 1 2 0x00 0x00 //where the 2 is it reads in 0x27 as a string

So, I am trying to figure out why it is reading in extra values instead of just the ones in the file.

void ioLoad(char* name)
{   
    std::ifstream inF;
    inF.open(name, ios_base::in);
    int i = 0;
    string rw;
    while(!inF.eof()){
        inF >> var.time[i]; //int time, from struct 'var'
        inF >> rw;          //string rw, should read either read or write
        inF >> std::hex >> var.address[i] //unsigned char address, from struct 'var' >>PROBLEM LINE<<
        if (rw == "write")
        {
            var.state[i] = WRITE; //stores an enum value as the state
            inF >> std::hex >> var.value[i];  //unsigned char value, from struct 'var' >>PROBLEM LINE<< 
        }
        printf("%d - %d %d 0x%02X 0x%02X\n", i, var.time[i], var.state[i], var.address[i], var.value[i]);
        i++
    }
    inF.close()
}

any help would be greatly appreciated and if you need more information please let me know.


Solution

  • var.address[i] and var.value[i] have type unsigned char. Your compiler treats chars as unsigned numerics. So the line inF >> std::hex >> var.address[i] reads chars. You could understand it just looking at the ASCII table.

    When inF >> std::hex >> var.address[i] performed, the input is 0x01 and '0' is placed to, that is 0x30. When inF >> std::hex >> var.value[i]; performed, the input is x01 and 'x' is placed to, that is 0x78.

    You can read into unsigned int tmp

    unsigned tmp;
    inF >> std::hex >> tmp;
    var.address[i] = static_cast<unsigned char>(tmp);
    if (rw == "write") {
      var.state[i] = WRITE;
      inF >> std::hex >> tmp;
      var.value[i] = static_cast<unsigned char>(tmp);
    }