#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。
最佳答案
你有两个问题:
cin >> input;
应该是std::getline(std::cin, input);
因为std::cin
会在第一个空格处停止,不存储字符串的其余部分。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;
}
正如@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;
}
关于c++ - 使用 incrimenter 计算空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40234657/