检测输入字符串是否有空格

Aks*_*sal -1 c++

我写了这段代码来检测输入字符串是否有空格。请说明这种方法有什么问题。

#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++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我输入带空格的字符串,则不会打印“空格”。

Tre*_*edJ 6

既然inp是std::string,inp[i]将是一个char。由于std::to_string仅对算术非char值具有重载,因此在char上调用它类似于在所述char的整数表示上调用它。(如果您登录z,则可能会找到一个打印的数字。)

而是直接比较inp[i]一个空格。 else { i++; }也是不必要的–您可能会跳过空间。

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

Run Code Online (Sandbox Code Playgroud)