简体   繁体   中英

Array and hex values C++?

I have a .txt with some numbers in hexadecimal and I put them into an array with ifstream . However, it doesn't print right, I mean, the numbers don't tally. This is my code:

void arrayNumbers(unsigned int longSize, unsigned int array[]) {
    file.open("hex.txt");
    int i;
    if(file){
        longSize=4; 
        array[longSize];
        for(int i=0;i<longSize;i++){ 
            file >> hex >> array[i];
            cout << array[i]<< endl; 
        }
        cout << "RIGHT" << endl;
    }
    else
        cout << "WRONG" << endl;

    file.close();
}

And in main() , I have:

void main() {
    unsigned int array[longSize];
    unsigned int longSize=4;
    arrayNumbers(longSize,array);
    cout << "OK" << endl;
}

What's happening here? TT

longSize=4; 
array[longSize];

This bit is completely wrong. Things you're trying to do here that you can't do:

  • Increase the size of an array at runtime (presumably your intent with the meaningless array[longSize] )
  • Choose the size of an array from a runtime value ( longSize )

Consider a std::vector instead.

Furthermore, your main returns void instead of int (which is ill-formed) and the array inside main has the size of yet another runtime variable, which is declared after the array!

Finally, I strongly recommend using a conventional indentation and brace-formatting style, as yours is strange and makes the code hard to read.

The error is probably that you don't pass hex to cout before you print the numbers.

If cleaned your program a little:

#include <iostream>
#include <fstream>

using namespace std;

void arrayNumbers(unsigned int longSize, unsigned int array[]) {
    fstream file("hex.txt");
    if (file){
        for (int i = 0; i < longSize; i++){
            file >> hex >> array[i];
            cout << hex << array[i] << endl;
        }
        cout << "RIGHT" << endl;
    } else {
        cout << "WRONG" << endl;
    }
}

void main() {
    const size_t longSize = 4;
    unsigned int array[longSize];

    arrayNumbers(longSize, array);
    cout << "OK" << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM