I am taking a course in c++ programming by IBM through edX. A majority of the program are hands-on exercises where one writes code to meet specifications, for a desired output given input, with samples of both provided. An online compiler is used to execute and evaluate the code.
I took code from a cook-book to split a string. As far as I can tell, the code should work. When I compile it though, the compiler runs out of memory, which I believe has 512 mb allocated to it. As the compiler is a service provided, I cannot allocate memory to it or change any settings. It is also the compiler I am required to use for the course. I asked on the course discussion board why my code is causing problems, but I have had no responses. I would like to know if the problem is the compiler and platform, or if I have a problem in my code.
I pared down the code to just what is needed for splitting a string, which is causing the memory allocation problems.
#include <iostream>
#include <string.h>
#include <vector>
#include <functional>
using namespace std;
void split(const string &s, char c, vector<string> &v)
{
string::size_type i = 0;
string::size_type j = s.find(c);
while (j != string::npos)
v.push_back(s.substr(i, i - j));
i = ++j;
j = s.find(c, j);
if (j == string::npos)
{
v.push_back(s.substr(i, s.length()));
}
}
int main()
{
// Fill the code here
// Strings
string prompt1 = "Enter name: ";
string prompt2 = "Enter roll number: ";
string prompt3 = "Enter Date of Birth [DD MM YY] format: ";
vector<string> v;
string s = "Something To Put Here";
split(s, ' ', v);
for (int i = 0; i < v.size(); ++i)
{
cout << v[i] << endl;
}
return 0;
}
So, is it the code or is it the platform?
The following code causes an infinite loop.
Since the
whileloop is not enclosed in braces, only the statement following thewhileloop is part of the loop. The variablejis not updated in the loop, it will never be equal tostring::npos, causing an infinite loop.Also,
s.substr(i, i - j)is incorrect sincei - jwill give a negative length. It should bes.substr(i, j - i)Following loop should work as expected