-3

I'm pretty new to coding and I'm not entirely sure how to do this. I have a .txt file filled with hex values. I need to load these values and store them in a C style array, with each value being separated with a comma. The array must be one dimensional, so if it were to be printed to command line, all the values would be on the same line. I've seen examples with two dimensional arrays and using ifstream, but I can't seem to get my head around putting the values into a 1D array.

The .txt file I'm using can be found here: https://drive.google.com/open?id=1dhNf00jookFqxnBwFhuL9VGpAjvRV2Pm

Thanks for any help.

2
  • You can look into this post here (stackoverflow.com/questions/14940633/…) on StackOverflow: Commented Nov 26, 2017 at 22:49
  • 2
    This is not a code writing service. What did you try so far? Post your code! What happened when you ran it? What did you expect to happen instead? What specifically are you having problems with? stackoverflow.com/help/mcve Commented Nov 26, 2017 at 22:51

2 Answers 2

1

To put the values in a 1D array, all you need to do is append to the end of the array every time you read a new value. Something like this for an std::vector:

#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <iomanip>

int main()
{
  std::ifstream fin("HexFile.txt");
  std::string s;
  std::vector<int> result;
  while(fin >> s)
  {
     result.push_back(GetHex(s));
     std::cout << s << "   "  << GetHex(s) << "\n";
  }
  return 0;
}

Where GetHex extracts the integer from the string with the comma. If you really need to use a C-style array, you need to either read the file twice or put the size of the input at the top of the file, because you need to know the size of a C-style array before you fill it out.

Sign up to request clarification or add additional context in comments.

Comments

0

To achieve what you need you could do something like this:

std::fstream file("somefile.txt");
std::string line;
std::vector<int> lines;
while(file >> line) lines.push_back(GetHex(line));
int results[lines.size()];
for(int i = 0; i<lines.size(); ++i) results[i] = lines[i];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.