c++ - 使用 incrimenter 计算空格

标签 c++

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string> using namespace std;

using namespace std;

int main()
{
int spaces = 0;
string input;
cin >> input;

for (int x = 0; x < input.length(); x++) {
    if (input.substr(0, x) == " ") {
        spaces++;
    }
}
cout << spaces << endl;
system("pause");
return 0;   
}

我正在尝试制作一个简单的程序,通过添加到增量器来计算空格的数量。

由于某种原因它总是返回 0。

最佳答案

你有两个问题:

  1. cin >> input; 应该是 std::getline(std::cin, input); 因为 std::cin 会在第一个空格处停止,不存储字符串的其余部分。
  2. if (input.substr(0, x) == "") 我无法理解您所说的这个表达式的含义。但是,您想要的是 if (input[x] == ' ')

完整代码:(略有改动)

#include <iostream>
#include <iomanip>
#include <string>     
int main(){
    unsigned int spaces = 0;
    std::string input;
    std::getline(std::cin, input);
    for (std::size_t x = 0; x < input.length(); x++) {
        if (input[x] == ' ') {
            spaces++;
        }
    }
    std::cout << spaces << std::endl;
    system("pause");
    return 0;   
}

Online Demo


正如@BobTFish 提到的,在实际代码中正确的做法是:

#include <iostream>
#include <string>   
#include <algorithm>
int main(){
    std::string input;
    std::getline(std::cin, input);
    const auto spaces = std::count(input.cbegin(),input.cend(),' ');
    std::cout << spaces << std::endl;
    system("pause");
    return 0;   
}

Online Demo

关于c++ - 使用 incrimenter 计算空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40234657/

相关文章:

c++ - 为什么bool和_Bool在内存中占用1个字节只能存储0或1?

C++ 将源文件中的某些函数设为私有(private)的最佳方法是什么?

c++ - 将继承的参数传递给基类构造函数,然后在派生类构造函数中做一些事情

c++ - 无法将 std::min 传递给函数,std::min 的拷贝有效

c++ - 写入默认构造的 fstream : Undefined Behavior?

c++ - Qt 我可以以编程方式设置资源吗?

c++ - 头文件中的外部枚举

c++ - 如何为元素( vector 和整数)也是 unique_ptr 的对创建 unique_ptr?

c++ - std::any 用于仅移动模板,其中 copy-ctor 内的 static_assert 等于编译错误,但为什么呢?

c++ - 谁能帮我解释一下C++中typedef的用法?