注册 登录
编程论坛 C++教室

求大神指点我的代码错在哪,感谢!

Hee麦 发布于 2012-12-27 13:57, 345 次点击
这个是我做C++PrimerPlus(第五版)第9章的第2道编程题的代码

#include <iostream>
#include <string>

void strcount(string s);

int main()
{
    using namespace std;
    string str;

    cout<<"Enter a line: \n";
    getline(cin,str);
    while(cin)
    {
        strcount(str);
        cout<<"Enter next line (empty line to quit): \n";
        getline(cin,str);
    }
    cout<<"Bye\n";
    return 0;
}

void strcount(string s)
{
    using namespace std;
    static int total=0;
    int count=s.size();
    total+=count;

    cout<<"\""<<s<<"\" contains "<<count<<" characters\n";
    cout<<total<<" characters total\n";
}

只有本站会员才能查看附件,请 登录


6 回复
#2
rjsp2012-12-27 14:05
程序代码:
#include <iostream>
#include <string>

void strcount( std::string s );

int main()
{
    using namespace std;

    cout<<"Enter a line: \n";
    for( string str; getline(cin,str); )
    {
        strcount(str);
        cout<<"Enter next line (empty line to quit): \n";
    }
    cout << "Bye" << endl;

    return 0;
}

void strcount( std::string s )
{
    using namespace std;

    static size_t total = 0;
    size_t count = s.size();
    total += count;

    cout<<"\""<<s<<"\" contains "<<count<<" characters\n";
    cout<<total<<" characters total\n";
}
#3
Hee麦2012-12-27 15:30
回复 2楼 rjsp
没能实现空行就结束程序这个功能 请问怎么修改可以实现?
#4
rjsp2012-12-27 15:59
以下是引用Hee麦在2012-12-27 15:30:13的发言:

没能实现空行就结束程序这个功能 请问怎么修改可以实现?

for( string str; getline(cin,str); )
改为
for( string str; getline(cin,str) && !str.empty(); )
试试
#5
manylong2012-12-27 16:29
学习ing
#6
Hee麦2012-12-27 17:59
回复 4楼 rjsp
谢谢,可以实现了,不过有个问题是getline()函数会保留回车符,下次读取先读取了回车符
只有本站会员才能查看附件,请 登录


我就在for()中加了一句cin.get(),即改为
for( string str; getline(cin,str) && !str.empty(); cin.get())
运行结果是:
只有本站会员才能查看附件,请 登录


就是说输入字符串后 要按2次回车它才显示下一句,
只有本站会员才能查看附件,请 登录

怎么解决这个问题,还是说这是VC6版本的bug,其他版本没问题?
#7
rjsp2012-12-28 08:43
回复 6楼 Hee麦
你还是换个编译器吧
1