标题:菜鸟问题,关于string类的一个小程序
取消只看楼主
迷途的菜鸟
Rank: 2
等 级:论坛游民
帖 子:36
专家分:50
注 册:2012-3-20
结帖率:83.33%
已结贴  问题点数:40 回复次数:1 
菜鸟问题,关于string类的一个小程序
程序代码:
#include <iostream>
#include <string>

void strcount(const string test);
int main(void)
{
    using namespace std;
    string str1;

    cout << "enter a string (empty line to terminate input):" << endl;
    getline(cin, str1)
    while (str1 != "")
    {
        strcount(str1);
        cout << "enter next line:" << endl;
        getline(cin, str1);

    }
    cout << "done!";

    return 0;
    
}

void strcount(const string test)
{
    int count = 0;
    static int total = 0;
    for (int i = 0; i < test.size(); ++i)
    {
        ++count;
    }
    cout << "current char is " << count << endl;
    total += count;
    cout << "total char is " << total << endl;

}

我的意图是这样,输入一行,不管多少个字符,统计输入的字符个数,然后继续输入,统计第二次输入行的字符个数,并且统计前两次输入的总字符数。依次继续,直到输入一个空行,输入结束。只用string类完成,不用数组之类的!代码附上。麻烦来个人指教一下,谢谢了!初学C++感觉有点不适
搜索更多相关主题的帖子: test 
2012-12-20 16:46
迷途的菜鸟
Rank: 2
等 级:论坛游民
帖 子:36
专家分:50
注 册:2012-3-20
得分:0 
以下是引用fxbszj在2012-12-20 20:21:58的发言:

#include <iostream>
#include <string>
using namespace std;  //注意位置

void strcount(const string test);
int main(void)
{
   
    string str1;

    cout << "enter a string (empty line to terminate input):" << endl;
    getline(cin, str1);  //你这里少个分号
    while (str1 != "")
    {
        strcount(str1);
        cout << "enter next line:" << endl;
        getline(cin, str1);

    }
    cout << "done!";

    return 0;
   
}

void strcount(const string test)
{
    int count = 0;
    static int total = 0;
    for (int i = 0; i < test.size(); ++i)
    {
        ++count;
    }
    cout << "current char is " << count << endl;
    total += count;
    cout << "total char is " << total << endl;

}
好像这样就可以了,你试试

程序代码:
#include <iostream>
#include <string>

void strcount(const string test);
int main(void)
{
    
    string str1;
    using namespace std;
    cout << "enter a string (empty line to terminate input):" << endl;
    getline(cin, str1).get();
    while (str1 != "")
    {
        strcount(str1);
        cout << "enter next line:" << endl;
        getline(cin, str1).get();
        
    }
    cout << "done!";
    
    return 0;
    
}

void strcount(const string test)
{
    using namespace std;
    int count = 0;
    static int total = 0;
    for (int i = 0; i < test.size(); ++i)
    {
        ++count;
    }
    cout << "current char is " << count << endl;
    total += count;
    cout << "total char is " << total << endl;
    
}

你好,我using namespace在main()和被调函数里都用一个,为什么会报错呢?
2012-12-20 21:23



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-392428-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.502168 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved