C++ 用犯罪中心点算空格 #包括“stdafx.h” #包括 #包括 #包括使用名称空间标准; 使用名称空间std; int main() { int空间=0; 字符串输入; cin>>输入; 对于(int x=0;x>input;应该是std::getline(std::cin,input);因为std::cin将在第一个空格处停止,而不存储字符串的其余部分 if(input.substr(0,x)==”)我不明白这个表达式的意思。但是,你想要的是if(input[x]='')
完整代码:(有小改动)C++ 用犯罪中心点算空格 #包括“stdafx.h” #包括 #包括 #包括使用名称空间标准; 使用名称空间std; int main() { int空间=0; 字符串输入; cin>>输入; 对于(int x=0;x>input;应该是std::getline(std::cin,input);因为std::cin将在第一个空格处停止,而不存储字符串的其余部分 if(input.substr(0,x)==”)我不明白这个表达式的意思。但是,你想要的是if(input[x]=''),c++,C++,完整代码:(有小改动) #包括 #包括 #包括 int main(){ 无符号整数空间=0; std::字符串输入; std::getline(std::cin,输入); 对于(std::size_t x=0;x>input;应该是std::getline(std::cin,input);因为std::cin将在第一个空格处停止,而不存储字符串的其余部分 if(input.substr(0,x)==”)我不明白这个表达式的意思。但是,你想要的是if(input[x]='') 完整代码:(有小改动
#包括
#包括
#包括
int main(){
无符号整数空间=0;
std::字符串输入;
std::getline(std::cin,输入);
对于(std::size_t x=0;x
cin>>input;
应该是std::getline(std::cin,input);
因为std::cin
将在第一个空格处停止,而不存储字符串的其余部分
if(input.substr(0,x)==”)
我不明白这个表达式的意思。但是,你想要的是if(input[x]='')
完整代码:(有小改动)
#包括
#包括
#包括
int main(){
无符号整数空间=0;
std::字符串输入;
std::getline(std::cin,输入);
对于(std::size_t x=0;x 顺便说一句,我明白你这样做只是为了学习,但在“真实”代码中,你应该只是使用。另外,请重新考虑一下你使用的通常被认为是不好的做法:和(这些是解释的链接)。顺便说一下,我明白你这样做只是为了学习,但在“真实”代码中代码,您应该只使用。另外,请重新考虑您对通常被认为是不好的做法的使用:和(这些是指向解释的链接)。我将把for循环编写为for(const auto c:input){if(c=''){spaces++;}
@MartinBonner:为什么?@ChristianHackl因为它更精确地表示for循环在做什么:遍历字符串中的每个字符。字符串的索引不相关。它更短的事实是一个额外的好处。@MartinBonner:反过来。std::count
版本清楚地说明了正在做什么,例如,计算空间。
版本的表示它是如何完成的,即使用条件分支、迭代和增量操作。这是一个以实现为中心的观点。std::count
版本是一个以接口为中心的观点。顺便说一句,如果我们谈论的是“正确的方法”,然后请删除系统(“暂停”)
。我会将for循环写为for(const auto c:input){if(c='''{spaces++;}}
@MartinBonner:为什么?@ChristianHackl因为它更精确地表示for循环在做什么:遍历字符串中的每个字符。字符串的索引不相关。它更短的事实是一个额外的好处。@MartinBonner:反过来。std::count
版本清楚地说明了正在做什么,例如,计算空间。
版本的表示它是如何完成的,即使用条件分支、迭代和增量操作。这是一个以实现为中心的观点。std::count
版本是一个以接口为中心的观点。顺便说一句,如果我们谈论的是“正确的方法”,然后请卸下系统(“暂停”)
。
#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;
}
#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;
}
#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;
}