#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;
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试制作一个简单的程序,通过添加到增量器来计算空格数.
由于某种原因它总是返回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;
}
Run Code Online (Sandbox Code Playgroud)
正如@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;
}
Run Code Online (Sandbox Code Playgroud)