-1

Essentially I'm creating my own string class called MyString. Within this class there is a function called getline which is supposed to perform exactly like the 'string' class's getline function does.

But upon testing, it seems the function doesn't exit the loop when it reaches a null character or the specified delimiter, and instead continuously prompts for input, and adds that input onto the already existing string (c-string).

istream& getline (istream& is, MyString& stringC, char delim){
    int i = 0;
    do{
        is.get(stringC.stringM[i]);
        i++;
        if(i == stringC.Size){
            stringC.Grow(1);
        }
    }while(is.peek() != '\0' || is.peek() != delim);
    stringC.stringM[i] = '\0';
    return is;
}

I have since fixed my last problem, but now my main simply closes after my last getline call.

cin >> s1;
getline(cin,s2,',');
getline(cin,s3); 
//It ends here

cout << "\nNew string values:\n";

cout << "s1 = " << s1 << '\n';
cout << "s2 = " << s2 << '\n';
cout << "s3 = " << s3 << '\n';
cout << "---------------------------\n";
Quantum
  • 1
  • 1

1 Answers1

0

It's a logic error:

is.peek() != '\0' || is.peek() != delim

if is.peek()== '\0', then it won't equaldelim(unless is also '\0') ifis.peek() == delim, then it won't equal '\0' (again, unless is also '\0')

You are looking for:

is.peek() != '\0' && is.peek() != delim

This terminates the loop if is.peek() is equal to '\0' or delim