-1

How should i go about loading a variable from a string?: for example, this is my text file:

int: 10
int: 25
int: 30

How could i load these into a array? this is the code i use to load the strings:

string loadedB[100];
ifstream loadfile;
loadfile.open("ints.txt");

if(!loadfile.is_open()){
    MessageBoxA(0, "Could not open file!","Could not open file!", MB_OK);
    return;
}

string line; int i = -1;
while(getline(loadfile, line)){ i++;
    loadedB[i] = line;
}
loadfile.close();

for(int x = 0; x < count(loadedB); x++){
    cout << loadedB[x] << endl;
}

I would like to do something like:

int intarray[100];   
loadfromstringarray(loadedB, intarray); 

That code would take the part of the string ( the numeric one ) and would put that value into the array, like intarray[0] = 10; and so on

EDIT: istringstream is the solution!

  • 2
    You want a [`std::istringstream`](http://en.cppreference.com/w/cpp/io/basic_istringstream). – πάντα ῥεῖ May 20 '16 at 20:09
  • 1
    But then the question is, how does he convert the stringstream data into individual ints? std::stoi() can work with your existing approach - http://www.cplusplus.com/reference/string/stoi/ – Serge May 20 '16 at 20:11
  • @πάνταῥεῖ thanks, that's what i was looking for! – Cornelius Aurel May 20 '16 at 20:16
  • Possible duplicate of [How to parse a string to an int in C++?](http://stackoverflow.com/q/194465/34255360) – Emil Laine May 20 '16 at 20:17
  • 1
    @CorneliusAurel Glad to help. You're well encouraged to write your own answer here showing the now working code, instead of stating that your problem was solved in your question. You should note that the site is primarily about building a FAQ like repository, rather providing a personal help desk. – πάντα ῥεῖ May 20 '16 at 20:20
  • @CorneliusAurel If you're accepting that `istringstream` is the answer please accept [Thomas Matthews' answer](http://stackoverflow.com/a/37355396/2642059) – Jonathan Mee May 20 '16 at 20:34

3 Answers3

1

I personally like the good old std::istringstream object:

const std::string  example = "int: 10";
std::string prompt;
int value;
std::istringstream parse_stream(example);
std::getline(parse_stream, prompt, ':');
parse_stream >> value;
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
0

I personally like the good old sscanf C function:

int intarray[100];
int i = 0;
while(getline(loadfile, line) && i < sizeof(intarray)/sizeof(*intarray))
{
    sscanf(line.c_str(), "int: %d", intarray + i++);
}
Aconcagua
  • 24,880
  • 4
  • 34
  • 59
0

Use stoi:

vector<int> ints;
ifstream loadfile("ints.txt");

string line;
while(getline(loadfile, line)) {
    ints.push_back(stoi(line.substr(5))); // skip the first 5 chars of each line
}

for(int i : ints) {
    cout << i << endl;
}

Output:

10
25
30
Emil Laine
  • 41,598
  • 9
  • 101
  • 157