'Reading integers separated by space in C++ using strtok
I am trying to read various lines from the user using strtok but some kind of problem seems to be happenning and I can´t understand why the program doesn't even print the debug values I had. Hope that some of you can help with it.
char* token;
char line[256];
int operations;
int time, depN;
vector<int> dep;
cin >> operations;
cout << "number operations " << operations << endl;
for(int i = 0; i< operations; i++){
cin.getline(line,256);
token = strtok(line, " ");
cout << token << "--" << endl;
time = stoi(token);
while((token=strtok(nullptr, " ")) != nullptr){
if(!flag){
depN = stoi(token);
cout << "DepN: " << depN << endl;
flag = true;
}else{
dep.push_back(stoi(token));
}
}
...
dep.clear();
}
Solution 1:[1]
Looks like the token is space. You can use stringstream.
for(int i = 0; i < operations; i++) {
std::string line;
if (std::getline(cin, line)) {
std::stringstream ss(line);
if (ss >> time) {
int token;
while (ss >> token) {
dep.push_back(token);
}
}
}
}
Not sure what flag is for so I left that out.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Johnny Mopp |
