【问题标题】:After counting characters counter stuck?计数字符后计数器卡住了?
【发布时间】:2017-02-18 23:00:05
【问题描述】:

大家好,我有以下代码,我不明白为什么在函数“strcount”中最后一行没有再次显示整个字符串? 提前致谢!

#include  <iostream>
const int ArSize = 10;
void strcount(const char * str);

int main()
{
    using namespace std;
    char input[ArSize];
    char next;

    cout << "Enter a line:\n";
    cin.get(input, ArSize);
    while(cin)
    {
        cin.get(next);
        while(next != '\n')
            cin.get(next);
        strcount(input);
        cout << "Enter next line (empty line to quit):\n";
        cin.get(input, ArSize);
    }
    void strcount(const char * str)
    {
        using namespace std;
        static int total = 0;
        int count = 0;

        cout << "\"" << str <<"\" contains ";
        while(*str++)
            count++;
        total += count;
        cout << count << " characters\n";
        cout << total << " characters total\n" << endl;
        cout << str << endl;
    }

【问题讨论】:

  • 调试器是解决此类问题的正确工具。 询问 Stack Overflow 之前,您应该逐行逐行检查您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
  • 您为什么希望cout &lt;&lt; str 打印原始字符串?您确实意识到您正在修改while 循环中的str 指针,对吧?
  • 我推荐使用std::stringstd::getline 来读取用户的文本。比担心数组溢出或丢失 nul 终止字符要容易得多。

标签: c++ pointers char constants increment


【解决方案1】:

在函数strcount

while(*str++)

递增str,直到到达字符串的末尾。

然后尝试输出

cout << str << endl;

不会显示任何内容,因为str 现在指向字符串的末尾。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 2016-05-26
    • 2020-11-13
    相关资源
    最近更新 更多