Why do I keep receiving error messages? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why do I keep receiving error messages?

My code works and outputs properly in my testing, but I also get an error message and I'm not sure why. #include <iostream> #include <string> using namespace std; int main() { cout<<"Please write a sentence"<<endl; string base; cin>>base; for (int i=0; i<base.length();i++) {cout<<base[i]<<endl;} }

30th Mar 2023, 12:30 AM
Lucien Keating
Lucien Keating - avatar
2 Answers
+ 4
The code shouldn't generate any error message till the time input is given properly. If you mean the warning generated by the compiler then that is due to the fact that your variable "i" is of type signed integer and "base.length()" returns an unsigned type, so you can't always compare the two as one can't be implicitly converted to other. A simple fix is to either cast the value returned by "base.length ()" to int or more preferably, convert "i" to an unsigned type.
30th Mar 2023, 12:52 AM
Arsenic
Arsenic - avatar
+ 3
// std::size_t can store the maximum size of a theoretically possible object of any type (including array) for (size_t i=0; i<base.length(); i++) cout<<base[i]<<endl;
30th Mar 2023, 12:38 AM
SoloProg
SoloProg - avatar