-22

My Need:

Using a while loop greet as many names as that are available on the stdin. Stop when you read the string '42' as a name.

My Coding:

#include<iostream>
using namespace std;
int main()
{
    int input=1;
    int i= 0;
    string name;
    while(input<=i)
    {
        cin>>name;
        if(name=="42")
        {
             break;
        }
        else
        {
           cout<<"Hello "<<name<<"!";
           i++;
        }

    }
    return 0;
}

Result:

For input 42, test case is passed. For other input, test case failed. Please post your answer.

Answer After ~1 Year:

Very sorry for this question . This is I asked when I have 0 knowledge about C++. This may be useful for the freshers.

Alec
  • 8,529
  • 8
  • 37
  • 63
Kalaivanan
  • 459
  • 2
  • 8
  • 17

5 Answers5

5

Your loop is flawed

int input=1;
int i= 0;
string name;
while(input<=i)

as input is greater than i to start with

You think the test case works for 42 but actually the logic inside your loop is never executed. It is simply the case that the console output is the same (i.e. there is none) but your code never gets as far as the cin to check the input is 42

mathematician1975
  • 21,161
  • 6
  • 59
  • 101
2

Your code doesn't ever enter while since the condition is always false.

Just use,

....
while(1)
{
....

This will run your loop indefinitely, and break whenever 42 is encountered.

CinCout
  • 9,486
  • 12
  • 49
  • 67
1

Your code does not even run when you pass 42, because input is greater than i.

while(input<=i) // input = 1, i = 0, 1 > 0

What you probably want is an infinite loop:

while (true)
Maksim Solovjov
  • 3,147
  • 18
  • 28
0

Your Code has these Problems:

  • It won't enter the while loop as input is initialized to 1 and i is initialized to 0.While checking the condition *while(input<=i)*i.e., while(1<=0) which is false it won't execute the statements below.
  • -

My Solution:

 #include<iostream>
using namespace std;
int main()
{
int input=0;
int i= 1;
string name;
while(input<=i)
{
    cin>>name;
    if(name=="42")
    {
         break;
    }
    else
    {
       cout<<"Hello "<<name<<"!";
       i++;
    }

}
return 0;
}
  • Initializing input with 0 and i with 1 will give you the desired output.
PSN
  • 2,326
  • 3
  • 27
  • 52
0

First of all, Sorry for my basic question. The loop is not initiated. Because the input is 1 and i is 0. But the condition I given is input<=i. Because of the false condition, the control is not entering in loop

Kalaivanan
  • 459
  • 2
  • 8
  • 17