question
question

Reputation: 73

Need help C++ please, using bool etc

My task is: to write a program which reads characters one by one from the keyboard until the character ’q’ is entered. Use a loop with and bool variable for exiting the loop. At the end a string containing all entered letter should be printed on the screen (except the ’q’).

This is what i have so far and i am kind of stuck now, everytime i run it I am only able enter 1 character then the program stops---> this occurred after i wrote the last line with if(b==true)....... .

int main()
{
bool b;
char input[80];
int i;

b = false;
while(b != true){
    cout<<"Enter characters: "<<endl;
    cin>>input[i];
    if(input[i] == 'q'){
        b == true;
        break;
    }
}

if(b == true){
    for(int j = 0; j < 1; j++){
        for(int x = 0; x < 1; x++){
            cout<<input[i]<<endl;
        }
    }
}

Please help. Thank you very much.

Upvotes: 0

Views: 51

Answers (2)

selbie
selbie

Reputation: 104474

Six bugs.

  1. You forgot to initialize i to zero.

  2. You forgot to increment i on each pass of the loop

  3. Operator == is different than operator =.

  4. Bad things will happen if your input exceeds the size of your input array. Hence, some checks to make sure i does not exceed 80 (the declared length of your input array.

  5. You are inserting q into the input array, but you don't want to print it.

  6. Prompting for more characters on each iteration of the loop. Not sure if you meant this.

Some modifications to your loop:

i = 0;
b = false;
cout<<"Enter characters: "<<endl;
while (i < 80)  // limit to 80 chars
{
    char ch;
    cin >> ch;
    if(ch == 'q')
    {
        b = true;   // assign with =, not compare with ==
        break;
    }
    input[i] = ch; // insert into array after the check for q
    i++;  // increment i
}

Finally, your print loop is hopeless. Let's just safely null terminate your string and print it.

if(b)
{
    if (i >= 80)
    {
        i=79;
    }
    input[i] = '\0';
    cout << input << endl;
}

If you are familiar enough with the string class in C++, you could easily convert your code to use that. Then you won't have to deal with array limits of 80.

Upvotes: 2

user5478212
user5478212

Reputation:

use this code it will work as you wish.

#include <iostream>
using std::cout;
using std::cin;

int main()
{
    char input[80];
    int i = 0;

    input[i] = cin.get();

    while (input[i] != 'q')
    {
        i++;
        input[i] = cin.get();
    }

    for (int j = 0; j < i; j++)
    {
        cout << input[j];
    }

    system("Pause");
    return 0;
}

Upvotes: 0

Related Questions