#include <iostream>
#include<string>
using namespace std;
int main()
{
string x="";
cout<<"please enter a word\n";
cin>>x;
int no=x.size();
while(no>=5)
{
cout<<"good\n";
cin>>x;
int no=x.size(); //i want the while loop to stop after entering
//a word for the second time which has no.
// less than 5 but it doesnt
}
#include <iostream>
#include <string>
usingnamespace std;
int main() {
string x = "";
cout << "please enter a word\n";
cin >> x;
int no = x.size();
while(no >= 5) {
cout << "good\n";
cin >> x;
int no = x.size(); // i want the while loop to stop after entering
// a word for the second time which has no.
// less than 5 but it doesnt
}
cout << "small word\n";
return 0;
}
a- Compile with warnings enabled
$ g++ -W{all,extra,pedantic} foo.cpp
foo.cpp: In function ‘int main()’:
foo.cpp:13:7: warning: unused variable ‘no’ [-Wunused-variable]
¿why does it say that `no' is unused when it is part of the condition in line 10?
Because it is not the same variable. (check out: scope)
Line 13 is declaring another variable, if you want to just assign to the one that you already have, then drop the type specifier. no = x.size();
\alpha- Just drop the `no' variable and use `x.size()' instead
#include <iostream>
#include <string>
int main()
{
while (true)
{
std::string input = "";
std::cout << "please enter text of five or more characters: ";
std::getline(std::cin, input);
if (input.size() < 5)
{
std::cout << "\nThe input was too small, try again please\n";
}
else
{
std::cout << "\nThank you....exiting....\n";
break;
}
}
}
please enter a word of five or more characters: test
The input was too small, try again please
please enter a word of five or more characters: more test
Thank you....exiting....
But why in mine after i input x with no. less than 5, it still stays in the loop?
That's not what you have programmed it to do.
For instance if you type in 'four', no = 4, so the while test fails and you go straight to your line cout<<"small word\n";
please enter a word
four
small word
Exit code: 0 (normal program termination)
People have kindly taken the time and effort to explain why, in their replies to this thread. If you actually read those replies, you'd know the answer.