My problem is in the while (nombre[0] !='std::string
')
condition that apparently does not read it for some reason.
You have problems if you trust that condition.
If the std::string
is empty it will have no elements, no element. So accessing the first element of a% empty% co is causing a undefined behavior . For this reason, it could be that remains in a loop and never comes out , or it could launch a runtime error, or it could be invoked demons that would be fired from your nostrils .
The value is read, but we have described in the previous paragraph will be an indeterminate value that is almost never 'std::string
'
and consequently almost never leaves the loop even if the std::string
is effectively empty.
After describing the problem you are with, let's move on to the solutions. If we consult the documentation of empty
we see that it has several functions related to its capacity:
-
size
: Check if the string is empty.
-
length
, max_size
: Returns the number of characters stored.
-
reserve
: Returns the maximum number of characters the chain can store without exceeding the limits of the library or the implementation.
-
capacity
: Save memory to store more characters.
-
shrink_to_fit
: Returns the memory reserved for this string, whether it contains data or not. contains.
-
size
: Reduces the memory reserved by the string to equal the memory it contains data.
In your case only the functions length
, empty
and size
are relevant, which you could use in the following way:
0
while (nombre.size()){
cout<<nombre<<endl;
cout<<"ingrese una palabra "; cin>>nombre;
}
Integer values are implicitly convertible to a Boolean condition with a value false
interpreted as true
and any other value interpreted as size
; so: if 0
returns a value different from length
, it will remain in the loop, the same thing happens with:
empty
while (nombre.length()){
cout<<nombre<<endl;
cout<<"ingrese una palabra "; cin>>nombre;
}
Finally, we can know if it is empty also with the function empty
, but it requires us to invert the check (since we want the loop to continue while it is not empty):
%code%
while (!nombre.empty()){
cout<<nombre<<endl;
cout<<"ingrese una palabra "; cin>>nombre;
}