我的任务是
在C ++中,使用指针来计算用户输入的字符数。在屏幕上打印输出
这就是我所做的。我不知道如何计算输入的字符。
#include <iostream>
using namespace std;
int main()
{
int string[20] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
int sum = 0;
char a;
cout << "Enter less than 20 characters(no space) : ";
for (int i = 0; i < 20; i++)
{
cin >> a;
string[i] = a;
if (string[i] != 0)
sum = sum + 1;
else
break;
}
cout << endl;
cout << "The number of characters in " << *string << " is " << sum;
return 0;
}
答案 0 :(得分:0)
根据我对要求的理解,您将需要使用一个指针。
int main()
{
static const size_t MAX_CHARS = 20;
char text[MAX_CHARS] = {0};
std::cout << "Enter up to 20 characters, no spaces: ";
size_t quantity;
char c;
while (std::cin >> c)
{
if (quantity >= MAX_CHARS) break;
text[quantity++] = c;
}
// Count the characters using a pointer:
if (quantity < MAX_CHARS)
{
text[quantity] = '\0';
}
else
{
text[MAX_CHARS - 1] = '\0';
}
quantity = 0;
char * pointer = &text[0];
while (*pointer != '\0')
{
++quantity;
++pointer;
}
std::cout << "Characters entered: " << quantity << "\n";
return 0;
}
我想这是理解指针的练习。
否则,我建议使用std::string
和std::string::length()
。