-2
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>

using namespace std;

int main()
{
    system("cls");
    ofstream dat_in;
    dat_in.open("zd4.txt");
    dat_in << "";
    char sentence[500] = "";

    while (sentence[0] != '*' && strlen(sentence) != 1)
    {
        cout << "Input sentence: ";
        cin.getline(sentence, 500);
        if (sentence[1] != '*' && strlen(sentence) != 1)
            dat_in << sentence<< "#";
    }
}

(I'm not really good at C++ so please bear with me) The while loop above should stop executing when the inputted sentence is simply "*" but it ends whenever the sentence is 1 character long. I've tried doing sentence!="*" but it did not work and the loop would never end. What is the problem here? Is there an easier way of doing it?

thejj
  • 43
  • 3
  • Have you tried stepping through the code with a debugger? – Quimby May 28 '22 at 15:10
  • 1
    Let's say you enter the character `A`. `sentence[0] != '*'` will be `true`, but `strlen(sentence) != 1` will be `false` (since `strlen(sentence)` will be equal to `1`). `true && false` is always `false`, so the loop condition is not true, and the loop terminates. – Peter May 28 '22 at 15:16
  • 1
    What you probably want is `while ( sentence[0] != '*' || strlen(sentence) != 1 )`. However, I suggest that you use `while ( strcmp( sentence, "*" ) != 0 )` instead. – Andreas Wenzel May 28 '22 at 15:32

0 Answers0