0

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".

3
  • There is no need for incrementing "i" in the else clause. What are your results without it? It may be skipping the spaces altogether. Commented Jun 11, 2019 at 18:06
  • 1
    Answer given already, you might still want to consider 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 == ' ') .... Commented Jun 11, 2019 at 18:15
  • 1
    @Aconcagua std::string has its own find() method: inp.find(' ') Commented Jun 11, 2019 at 22:34

2 Answers 2

6

Since inp is an std::string, inp[i] will be a char. Since std::to_string only has overloads for arithmetic, non-char values, calling it on a char is akin to calling it on the integer representation of said char. (If you log z, you'll likely find a number printed.)

Instead, directly compare inp[i] to a space. else { i++; } is also unnecessary – you may be jumping over spaces.

for (int i = 0; i < inp.length(); i++) {
    if (inp[i] == ' ') {    // note single quotes for char
        cout << "space";
    }
}

Sign up to request clarification or add additional context in comments.

Comments

0

@TrebledJ's answer explains why your code is broken and how to fix it.

Another way to handle this situation is to use std::string::find() instead:

#include <iostream>
#include <string>

int main(){
    std::string inp;
    std::getline(std::cin, inp);

    if (inp.find(' ') != std::string::npos) {
        std::cout << "space";
    }
}

Alternatively, your original code tries to output "space" for each space character found. You could use find() in a loop:

#include <iostream>
#include <string>

int main(){
    std::string inp;
    std::getline(std::cin, inp);

    std::string::size_type idx = inp.find(' ');
    while (idx != std::string::npos) {
        std::cout << "space at " << idx << std::endl;
        idx = inp.find(' ', idx+1);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.