【发布时间】: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 << str打印原始字符串?您确实意识到您正在修改while循环中的str指针,对吧? -
我推荐使用
std::string和std::getline来读取用户的文本。比担心数组溢出或丢失 nul 终止字符要容易得多。
标签: c++ pointers char constants increment