I wrote this code to detect if an input string has a space or not. Please tell what is wrong in this approach.
#include <iostream>
#include <string>
using namespace std;
int main(){
string inp;
getline(cin, inp);
for (int i = 0; i < inp.length(); i++) {
string z = to_string(inp[i]);
if (z == " ") {
cout << "space";
}
else {
i++;
}
}
}
If i enter a string with spaces, it doesn't print "space".
std::find(inp.begin(), inp.end(), ' ')– and if you don't want to, you might consider a range based for loop:for(auto c : inp) { if(c == ' ') ....std::stringhas its ownfind()method:inp.find(' ')