我如何才能以正确的方式编写此程序? [英] HOW i can write this program in a correct way?
本文介绍了我如何才能以正确的方式编写此程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include "stdafx.h"
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int jomleTokalame(string *a){
string s = "";
int count = s.length();
string::iterator i;
int Count = 0;
for (i = s.begin(); i != s.end(); i++)
{
if(*i != ' ' && *i != '.')
{
Count++;
}
}
cout<<Count<<endl;
}
int main()
{
string a;
string s="salam";
int g;
cout<<jomleTokalame()<<endl;
}
推荐答案
哇,该代码甚至无法编译. c是一个int变量.因此,您无法像在该代码中那样像指针/数组一样访问它.那只是代码中最明显的错误,我敢肯定,还有其他问题.
您能否确切说明您要在这里做什么?
~~~~~~~~
如果只需要字符串的长度,则只需一行代码即可:
Wow, that code will not even compile. c is an int variable. So you cannot access it like a pointer/array as you have in that code. That''s just the most glaring error in the code, I am sure there are other problems too.
Can you restate exactly what it is you are trying to do here?
~~~~~~~~
If you just want the length of your string, it''s just one line of code to do that:
string s = "test";
int count = s.length();
~~~~~~~~~~
根据您最新的要求(不包括空格和点),可以执行以下操作:
~~~~~~~~~~
Based on your updated requirements not to include space and dot, here''s what you can do:
string s = "This is a test.";
int count = s.length();
string::iterator it;
int filteredCount = 0;
for (it = s.begin(); it != s.end(); it++)
{
if(*it != ' ' && *it != '.')
{
filteredCount++;
}
}
Nish的回答非常好.
或者,您可以使用标准的 std :: count_if [
Nish''s answer is excellent.
Alternatively you can use the standard std::count_if[^] algorithm.
Here is a quick example for you:
#include <iostream>
#include <string>
#include <algorithm>
// We will use this filter pradicate with std::count_if
bool filter(char arg)
{
// Accept all chars except spaces and dots
return arg != ' ' && arg != '.';
}
int main()
{
std::string str("Test test. Test test.");
// Count the symbols in the string using filter
std::cout << "Count: " << std::count_if(str.begin(), str.end(), filter);
return 0;
}
您会看到使用count_if
算法可以简化很多事情. ;)
You see that using the count_if
algorithm could simplify things a lot. ;)
在编辑您发布的代码时,我发现缺少一个右括号(花括号).那是你的问题吗?您收到任何编译错误了吗?
问候.
While editing the code you had posted I found that there was a missing closing brace (curly parenthesis). Was that your problem? Did you receive any compilation errors?
Regards.
这篇关于我如何才能以正确的方式编写此程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文