This is more of a correctness post, Hans has your problem.
The correct way to get a line of input is with getline
:
std::string s;
std::getline(std::cin, s);
std::cin
breaks at whitespace anyway, so if you typed asd 123
and ran your code, input_line
would first be "asd", then the second time in the loop "123" (without waiting for enter).
That said, an easy way to get your result is with a stringstream
. Any time you explicitly allocate memory, especially with malloc
, you're probably doing something the hard way. Here's one possible solution to tokenizing a string:
#include <sstream>
#include <string>
#include <iostream>
int main(void)
{
std::string input;
std::getline(std::cin, input);
std::stringstream ss(input);
std::string token;
while(std::getline(ss, token, ' '))
{
std::cout << token << "...";
}
std::cout << std::endl;
}
If you really want to use strtok
, you might do something like this:
#include <cstring>
#include <string>
#include <iostream>
#include <vector>
int main(void)
{
std::string input;
std::getline(std::cin, input);
std::vector<char> buffer(input.begin(), input.end());
buffer.push_back('\0');
char* token = strtok(&buffer[0], " ");
for (; token; token = strtok(0, " "))
{
std::cout << token << "...";
}
std::cout << std::endl;
}
Remember, manually memory management is bad. Use a vector
for arrays, and you avoid leaks. (Which your code has!)